views:

108

answers:

2

Hi folks,

I am trying to create some URL constraints for controllers to prevent null reference exceptions.

For example

/folder/edit/3 should be okay

/folder/edit/asdf shouldn't be okay

Instead of adding a Regex on every action method I want to use URL constraints for that.

The Problem I am facing right now is that the default route catches all requests, or if I am adding that constraint to the default route the standards request like http://host.tld/ aren't working anymore.

The constraint I am trying to add is

routes.MapRoute(
    "RouteWithContraint",
    "folder/edit/{id}",
    new { controller="folder", action="edit", id="" },
    new { id = @"\d+" }
);

Does anyone has a hint for me on how to solve that problem? Or maybe someone knows a best practice on DRY for "IsANumber" checks for ids?

best regards,

Gordon

+1  A: 

How about to create custom ActionFilterAttribute for checking the type for some actions and/or controllers? Example of OnActionExecuting method of class inherited from ActionFilterAttribute:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      if (filterContext.RouteData.Values["action"] == "edit" && !IsProperTypeofId()) 
         RedirectToRoute(filterContext, new { controller = "General", action = "Error", id = 401 });

      base.OnActionExecuting(filterContext);
    }
Andrey Tkach
An original approach +1 : )But i think is overwhelming, what do you think?Perhaps there is something we could do directly with routes..
SDReyes
Yep this is about the quick solution. Proper might be extending the routing functionality or so.
Andrey Tkach
+1  A: 

The order that the routes are added matters. As a request comes in, the routes are checked one after the other until a match is found. Therefore you need to order your routes from most specific to least specific.

You may already have tried this, but if you add your custom route before the default route, do you have more luck?

Matt Tester
Have you test this solution Randolpho? : O
SDReyes