Can Asp.Net Mvc Route Constraints throw a 404 instead of InvalidOperationException?

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?

Answers


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.


Need Your Help

iPhone: Building talking puppet application

iphone animation

I am trying to learn and build talking puppet iPhone application. The great example is "Talking Ben the Dog" and here is youtube video. I have no idea how am I going to build such application. I ha...

R dplyr summarise one column value based on index of fun(another column)

r dplyr

I have a data frame as this, and want the output as shown desired at the end. Instead, I get the NA output in the middle. Is there any way to do what I want using dplyr?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.