views:

1148

answers:

1

I'm trying to use route constraints in an Asp.Net MVC Application.

routes.MapRoute(
    "theRoute",
    "MyAction/{page}",
    new { controller = "TheController", action = "MyAction", page = 1 },
    new { page = @"[0-9]" });

When I enter an url like ~/MyAction/aString, an YSOD is shown with an invalid operation exception. What can I do to redirect invalid url to the 404 page?

I know I can solve the issue with a string parameter in the controller action and int.TryParse, but then the route constaint is useless.

How can I choose the exceptiontype that is thrown by the route constraints?

+2  A: 

The problem is that you do not have a route that matches the route that ends in a string.

Modify your routes similar to:

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = 0 },
    new { id = "[0-9]" }// Parameter defaults
);
routes.MapRoute(
    "Default2",                                              // Route name
    "{controller}/{action2}/{sid}",                           // URL with parameters
    new { controller = "Home", action = "Index2", sid = "" }  // Parameter defaults
);

and modify your controller

public ActionResult Index(int id)
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC! Your id is: "+ id.ToString();

        return View();
    }

    public ActionResult Index2(string sid)
    {
        ViewData["Title"] = "Home Page 2."+sid.ToString();
        ViewData["Message"] = "Welcome to ASP.NET MVC! \"" + sid.ToString() +"\" is an invalid id";

        return View("index");
    }

now when you pass a string for the ID, Index2 will be called and you can do whatever you need to do to handle the incorrect parameter.

Matthew