ASP.Net MVC - How to validate the route values? Can I control the routes using the type of the values?

By [)ia6l0 iii

One of the best ways is to use the RouteConstraint to validate the route values and then choose a route to controller. Route values that hold values of integer is the best example. If the route value is passed as string which cannot be converted to an Integer, we suffer with run-time and unhandled exceptions on our code.

The fourth parameter in the MapRoute functions takes Constraints - And here it is a custom constraint that is applied to the File Id. The regex validates for integer.
routes.MapRoute(
               "fileDeleteRoute", "file/delete/{fileId}", new { controller = "file", action = "delete", fileId = 0 },
               new { fileId = new FileIdConstraint(@"^\d+$")});

The FileIdConstraint class needs to use the IRouteConstraint interface as shown below.

public class FileIdConstraint : IRouteConstraint
{
        private string idRegEx = string.Empty;
       public FileIdConstraint(string regEx) {
            idRegEx = regEx; }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {
            bool returnValue = false;
            if (values.ContainsKey(parameterName)) {
                returnValue = Regex.IsMatch(values[parameterName] as string, idRegEx); }
            return returnValue;}
}

Related FAQs

If you browse your mvc pages, through modern day browsers like Chrome - you will find that there would be additional requests like the ones to the favicon. This is the icon, that appears to the left of the web address in the browser once the page loads.
Use the ContentEncoding property of the webresponse to figure out if the response is gzip compressed
ASP.Net 4.0 provides the SetSessionStateBehavior method through the HTTPContext Class.
Use the Override versions of the page methods instead of thedefault page methods. This would ensure that the .Net runtime does not have to invoke delegates.
Use the FilePathResult to return a file content as the http response.
You can check the contenttype of the request, and figure out if the request is an JSon request
ASP.Net MVC - How to validate the route values? Can I control the routes using the type of the values?  (2469 Views)