Search
Close this search box.

Url Rewriting Using ASP.NET MVC Framework

Few days ago I wrote a post about Url Rewriting Using RewritePath Method. The basic idea was to rewrite the path to the correct one inside the Application_BeginRequestPath method. This worked out okay but the string manupilation was a bit ugly.

ASP.NET MVC Framework gives you the complete control over the URL’s. So, you can easily change the URL to anything you like. Let’s say I have a url like the following:

Articles/[id]

and I like to to display the URL like this:

Articles/[id]_[title of the article]

For this to work we need to add a new route entry in the route table as shown below:

RouteTable.Routes.Add(new Route

 {
                Url = "Articles/[title]",
                Defaults = new { controller = "Articles", action = "Details", title = (string)null },
                RouteHandler = typeof(MvcRouteHandler)
            });

In the code above I have added the title anonymous type to be displayed in the URL. Now, I need to recreate the URL so when the user clicks the artilcle he/she is redirected to the correct article. Here is the page that list all the articles.

<% foreach (var article in ViewData)
       {
          
      %>
     
      <li>
      <%= Html.ActionLink(article.Title, new { controller = "Articles", action = "Details", title = (article.ArticleID+"_"+article.Title).Replace(" ","_")
         }) %>
      </li>
      
       <% } %>

The title is generated using the ArticleID and the Title fields. It should look something like this:

Articles/120_Introduction_To_C_Sharp_Programming

Now, let’s see the Details action which is triggered when the article is clicked.

 [ControllerAction]
        public void Details(string title)
        {

            int id = Int32.Parse(title.Split('_')[0]);
            var article = ArticleRepository.GetById(id);           
            RenderView("Details", article);            
        }

I extracted out the id from the URL and passed to the ArticleRepository.GetById method to get the particular article.

The ASP.NET MVC Framework gives us the flexibility to create our own URL’s and hence the more informative the URL is the better chances it has to be picked by the search engines.

This article is part of the GWB Archives. Original Author: AzamSharp

Related Posts