Url Rewriting Using ASP.NET MVC Framework

ew 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值