Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url routing to lowercase how to?


I have developed a Web Application on asp.net mvc3 and now i need to make routes, lowercased
Example:

 that's what i have:
 http://www.example.com/SubFolder/Category/Index => looks ugly :-)

 that's how i would like it:
 http://www.example.com/subfolder/category/index

I have found this post:
http://goneale.com/2008/12/19/lowercase-route-urls-in-aspnet-mvc/

I actually need to use the code inside the global.asax in the bottom of the page.

protected void Application_BeginRequest(Object sender, EventArgs e)   
{
    string lowercaseURL = (Request.Url.Scheme + "://" + 
    HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
    if (Regex.IsMatch(lowercaseURL, @"[A-Z]"))
    {
      lowercaseURL = lowercaseURL.ToLower() + HttpContext.Current.Request.Url.Query;
      Response.Clear();
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location", lowercaseURL);
      Response.End();
    }
}

Now is the question:
When is use it on dev station it's work's perfectly but when i upload it, to production it's not working .

On dev station it's makes only post but on the production it's does two:

POST - status: 301 Moved Permanently 
GET  - status: 200 OK

and i don't get redirected to the correct route at all. On the dev station it's works perfectly.

like image 830
hackp0int Avatar asked Dec 25 '11 07:12

hackp0int


2 Answers

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string lowercaseURL = (Request.Url.Scheme + 
    "://" +
    HttpContext.Current.Request.Url.Authority +
    HttpContext.Current.Request.Url.AbsolutePath);
    if (Regex.IsMatch(lowercaseURL, @"[A-Z]"))
    {
        System.Web.HttpContext.Current.Response.RedirectPermanent
        (
             lowercaseURL.ToLower() + HttpContext.Current.Request.Url.Query
        );
    }
}
like image 79
hackp0int Avatar answered Oct 03 '22 14:10

hackp0int


If this is simply for SEO, the easiest solution and the one I would use is to use url rewrite (assuming you are hosting on IIS) or mod rewrite (if you are hosting on Apache) to enforce lower case urls and leave posts as they are.

With IIS it's as simple as installing url rewrite from the web platform installer, hit add rule and select "enforce lowercase URLs". Easy.

If you upgrade to mvc4 and really want lowercase posts, there is a property LowercaseUrls which you can set to true when you register the routes. But again - I wouldn't bother.

like image 26
James Hull Avatar answered Oct 03 '22 13:10

James Hull