Labels

Monday, April 27, 2009

MVC || Routing || Custom Routing

Creating Custom Routes

 

For many simple ASP.NET MVC applications, the default route table will work just fine. However, you might discover that you have Specialized Routing Needs. In that case, you can create a custom route.

Imagine, for example, that you are building a blog application. You might want to handle incoming requests that look like this: /Archive/12-25-2009

When a user enters this request, you want to return the blog entry that corresponds to the date 12/25/2009. In order to handle this type of request, you need to create a custom route.

 

 

 

public void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

routes.MapRoute(

"Blog", // Route name

"Archive/{entryDate}", // URL with parameters

new { controller = "Archive", action = "Entry" } // Parameter defaults

);

 

routes.MapRoute(

"Default", // Route name – Line 1

"{controller}/{action}/{id}", // URL w/ params – Line 2

new { controller="Home", action="Index", id="" } // Param defaults – Line 3

 

);

}

 

protected void Application_Start()

{

    RegisterRoutes(RouteTable.Routes);

}

 

 

 

 

public class ArchiveController : Controller

{

public string Entry(DateTime entryDate)

{

   return "You requested the entry from " + entryDate.ToString();

}

}

 

 

 

The custom Blog route matches any request that starts with /Archive/. So, it matches all of the following URLs:

 

/Archive/12-25-2009

/Archive/10-6-2004

/Archive/apple – Produce Error for this one – as the URL cannot be converted to a DateTime

 

 

Creating a Route Constraint (C#)

 

As we saw above – the url '/Archive/apple' produces error - Because the Entry() action expects an integer parameter, making a request that contains something other than an integer value will cause an error.

To avoid this make a constraint – when defining a route to restrict the URLs that match the route.

 

"Only match URLs that contain a proper integer productId".

 

routes.MapRoute(

"Blog", // Route name

"Archive/{entryDate}", // URL with parameters

new { controller = "Archive", action = "Entry" }, // Parameter defaults

new { entryDate = @"\d{2} - \d{2} - \d{4}" }

);

 

This constraint causes the Archive route to not to match the URL -  '/Archive/apple'.

 

 

Creating a Custom Route Constraint

 

Reference: http://www.asp.net/learn/mvc/tutorial-25-cs.aspx

 

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

No comments:

Post a Comment