How to Rewrite URL using ASP.NET MVC


If you want your URL to looks like /2011/10/11/How-To-Code-Csharp. ASP.NET MVC's URL provide more simple way to rewriting your URL with less coding. This's about how to using ASP.NET MVC to rewriting your URL.

Before we going into how ASP.NET MVC how to work with URL rewriting, if you're interesting in how to use ASP.NET to rewrite your URL. You can look following blog article. How ASP.NET rewriting URL. Basically, there're following way to rewriting URL base on above blog.

  • use Request.PathInfo
  • use HttpModule
  • use HttpModule with IIS7
  • use ISAPIRewrite with IIS5, IIS6


Following are step how to rewrite your URL like /2011/10/11/How-To-Code-Csharp. Again,there're so many way we can do this.

Example: If you want your URL like this /2011/10/11/How-To-Code-Csharp.

1. adding Route.Table to Global.asax.cs.

Global.asax.cspublic static void RegisterRoutes(RouteCollection routes)
routes.MapRoute("Blog""{controller}/{action}/{year}/{month}/{day}/{title}"new { controller = "Home", action = "Blogs", id = "" });

2. How's Controller looks like.

Controller classpublic ActionResult Blogs(int year, int month, int day, int title)
var blogs = Data.GetBlog(year, month, day);
if (blogs.Count == 1) {
return View("Blog_Single", blogs[0]);
else if (blogs.Count > 1) {
return View("Blogs_Multi", blogs);
else { return View(); }

3. That's it!

click following button if you want to download this sample application.