Thursday, 3 May 2012

Tips for formatted urls in asp.net mvc

It wasn't long ago that applications built using Microsoft tools had some pretty unfriendly url's as standard (if you've used Webforms or "Classic ASP" you know what I'm talking about).

This was due to IIS' obsession with handler mappings and probably the general feeling that Webforms wasn't really suited for the Internet and therefore the benefits of better url's such as SEO were not as important. I suspect that back in the day, the Internet also wasn't as competitive for search rankings.

Yes - as with most things - there were ways around it. Personally, I used Helicon's ISAPIRewrite to make IIS behave a little bit more like Apache and have a more robust abstraction between the url that the user sees and the physical file that is serving the request.

With the release of ASP.NET MVC and IIS 7, extensionless urls were introduced as a first-class feature and seeing .aspx everywhere was a thing of the past. Unfortunately, you can still spot an MVC application in the wild because of the upper-case characters - it's not quite as easy as spotting a Webforms application (view-source, CTRL-f, viewstate) but it bothers me nonetheless.

This is a class I have used on a ton of projects to format the route as I think it should be:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace Core.Mvc
{
    public class FormattedRoute : Route
    {
        private readonly List<string> _formatExclusions = new List<string>();

        public FormattedRoute(string url, object defaults, object constraints = null, IEnumerable<string> formatExclusions = null, object dataTokens = null) :
            this(url, defaults, new MvcRouteHandler(), constraints, formatExclusions, dataTokens)
        {
        }

        public FormattedRoute(string url, object defaults, IRouteHandler routeHandler, object constraints = null, IEnumerable<string> formatExclusions = null, object dataTokens = null) :
            base(url, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new RouteValueDictionary(dataTokens), routeHandler)
        {
            if (formatExclusions != null)
                _formatExclusions.AddRange(formatExclusions);
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            foreach (var routeValue in requestContext.RouteData.Values)
            {
                if (_formatExclusions.Contains(routeValue.Key, StringComparer.OrdinalIgnoreCase)) continue;

                if (values[routeValue.Key] != null)
                    values[routeValue.Key] = values[routeValue.Key].ToString().ToLowerInvariant();
            }

            return base.GetVirtualPath(new RequestContext(requestContext.HttpContext, new RouteData()), values);
        }
    }
}
To use it, you would bootstrap the route from your Global.asax.cs file as follows:
routes.Add(new FormattedRoute("{controller}/{action}/{id}",
  new { controller = ControllerNames.Home, action = ActionNames.Default, id = UrlParameter.Optional }));
The custom route accepts much the same parameters as the default route or MapRoute call.

A key feature is the "formatExclusions" parameter which allows you to opt-out of the formatting on a key-by-key basis. Typically, this is used for proper-names so generated url's preserve the capitalisation.

An example of such a route is as follows:
    routes.Add(new FormattedRoute("p/{manufacturer}/{sku}/{productId}",
        new { controller = ControllerNames.Product, action = ActionNames.Default }, 
            constraints: null,
            formatExclusions: new[] {"manufacturer", "sku" }));
In this case, only the product id route value will be modified.

If you're wondering what the "ControllerNames" or "ActionNames" classes are - they are only constants which map to the real controller names. I find this gives a bit of extra compile-time assistance if I rename something and allows me to abstract the controller class names even further.

24 comments:

  1. For many websites, Google organic search results are the main source of traffic. This means that your site's content reaches advanced in search results and is well served by other search results. In this article, I will apply some basic SEO techniques and SEO services to the ASP.NET MVC so that Google's website and other search engines pages can be found potentially.

    ReplyDelete
  2. To create a successful website, in addition to high-quality content, good SEO strategies are equally vital. SEO works for your website as seasoning works for your food, and 247 Developers provide the finest SEO services to help you reach the high ranks on a search engine. Working on Google guidelines, we develop result-oriented SEO campaigns for our clients including complete on-page and off-page optimization. That is how 247 Developers provide the SEO Services in Pakistan.

    ReplyDelete
  3. Long & complex URLs are not user friendly as well as bad for the optimization of the website. To make a website user-friendly it is necessary for us now to keep our URL's user friendly and optimize images as well. top Seo companies keep in mind to make URLs simple by following the tips for formatted URLs in asp.net mvc and other languages too.

    ReplyDelete
  4. Very well said. SEO service is becoming and demanding nowadays. Everyone wants their business increase online presence. Hence, you promote your business online first you make a designed website then do SEO for ranking your website you need SEO guide to help you reach on a search engine.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. SEO Working with the site header section
    you need to know the Header of site for the SEO meta description, meta tags. SEO is the man thing for the getting more traffic on your Website or blog.
    Best SEO Services Provider Agency in Pakistan.
    ICREATIVEZ is the Award Winning Agency in SEO and Web Develeopment Agency 2020 by Clutch.

    ReplyDelete
  7. Archie 420 Dispensary is a trusted Cannabis dispensary base in Los Angeles California USA. It is one of the top dispensary in this part of the country. They do deliver Marijuana in the USA and to over 25 countries in the world. Buy Death Star weed online You can always visit their dispensary in Los Angeles using the address on their website. Place your order and get served by the best dispensary in the planet. Have fun.

    ReplyDelete
  8. Crystal online pharmacy is a trusted online drug store with a wide range of products to suit the needs of our clients. Buy research chemicals online Crystal Pharmacy do strive to offer the best service and ship products world wide. All the products listed on our website are Ava in stock. Expect your order to be processed Immediately when you send us your request. We deal with varieties of drugs for our customers satisfaction. We cross barriers with our products and struggle hard to meet human satisfaction. When shopping with us, Be safe and secured and you will realize how swift we are with our services.

    ReplyDelete
  9. 국내 최고 스포츠 토토, 바카라, 우리카지노, 바이너리 옵션 등 검증완료된 메이져 온라인게임 사이트 추천해 드립니다. 공식인증업체, 먹튀 검증 완료된 오라인 사이트만 한 곳에 모아 추천해 드립니다 - 카지노 사이트 - 바카라 사이트 - 안전 놀이터 - 사설 토토 - 카지노 솔루션.

    온라인 카지노, 바카라, 스포츠 토토, 바이너리 옵션 등 온라인 게임의 최신 정보를 제공해 드립니다.

    탑 카지노 게임즈에서는 이용자 분들의 안전한 이용을 약속드리며 100% 신뢰할 수 있고 엄선된 바카라, 스포츠 토토, 온라인 카지노, 바이너리 옵션 게임 사이트 만을 추천해 드립니다.

    ReplyDelete
  10. Great information, this information is necessary and essential for everyone. I am thankful for you for providing this kind of good information.Website Design Near Me

    ReplyDelete
  11. Hey There. I discovered your weblog using
    msn. This is a really neatly written article. I’ll make sure to bookmark
    it and return to read extra of your useful info. Thank
    you for the post. I’ll definitely comeback.
    website design and development company in pune

    ReplyDelete
  12. WebNagar provides the best SEO Expert in Karachi and globally. We've got well known SEO Experts awarded best SEO Agency in Karachi, Pakistan in 2019.

    ReplyDelete
  13. 토토사이트 이용을 하다 보면 먹튀 피해에 대한 두려움이 갑자기 생기거나 두려움을 가지고 이용하는 경우가 대반사입니다. 토토마추자는 그러한 두려움을 없애드리기 위해 만들어진 먹튀검증커뮤니티 입니다. 다양한 검증 활동을 통하여 축적된 데이터로 방문해 주시는 모든 회원님들께 무료로 제공해드리고 있습니다. 토토사이트를 이용 하는 회원님들은 메이저사이트를 이용하고 싶은 마음이 크다는 걸 알 수 있습니다. 하지만 해당 토토사이트가 메이저인지 아닌지 확인할 방법은 민간인에게 어려움이 있다는 걸 알 수 있습니다. 이용전 꼭 토토마추자를 통하여 먹튀검증 서비스를 받아보시기 바랍니다안전놀이터.
    국내에 합법 토토사이트는 배트맨토토 에서 발매하는 정식서비스만 이용을 할 수 있으나 배팅금액 제한이 있기에 우후죽순 사설토토사이트가 생겨나고 있습니다. 대체적으로 이를 방지를 하려면 배트맨토토 자체에서 배팅금액 한도를 늘리는 수밖에 없다고 생각됩니다.

    ReplyDelete
  14. The Toto site section should select the personal Toto address of the company that reviews the Safety game site. Since most online betting sites are private, it is difficult to determine the size or assets of a company. Please use sports betting using the first class site approved. 토토사이트 토토사이트 도메인 모음 안전놀이터

    ReplyDelete
  15. 777 CASINO - Suncity 888
    777 CASINO. 4 파라오카지노 hours ago. 777 CASINO. 1:00 PM. 777 CASINO CHEF CASINO. suncity888 12th Avenue, Las Vegas. Las Vegas NV 89109. Las Vegas United States.

    ReplyDelete
  16. Just 99 Web Design offers affordable web design packages for every business, from basic one-page websites to full eCommerce website design services. inexpensive web design companies

    ReplyDelete
  17. Ghostwriters are basically the professionals who write the content for you but does not put their name on the work or takes any credit for their writing. Ghost writing simply means professional who are hired to write your memories, blogs or speeches and many more such scripts for you and your brand but doesn’t tag themselves on the work or you can say they don’t take the credit for their work and you are not allowed to share your work anywhere else. Ebook Writing Services

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete