Change URL from controller?

Shimmy Weitzhandler picture Shimmy Weitzhandler · Nov 21, 2012 · Viewed 14.5k times · Source

Is there a way to change the current url params from the controller so when the page is loaded, additional/different parameters are displayed in the address bar?

Here's what I mean, say I have an action 'Products':

public ActionResult Product(int productId)
{
  ..
}

I mapped the routes so that product/4545/purple-sunglasses is mapped to the function above, the product name is actually ignored, but I want, that if the product name is not specified, the controller should add this, so the product gets in easily in search engines etc.

Answer

René Wolferink picture René Wolferink · Nov 21, 2012

Have a look here: http://www.dominicpettifer.co.uk/Blog/34/asp-net-mvc-and-clean-seo-friendly-urls

There is a very long description how to do it. And the last part tells you about 301-redirects, which you should use to instruct search engine crawlers that the page can be found under the desired URL you wish.

Don't forget to take a look at the url-encoding, should save you some work and provide higher quality urls.

Here are some essential snippets from the blog post:

Set up your routing:

routes.MapRoute( 
    "ViewProduct", 
    "products/{id}/{productName}", 
    new { controller = "Product", action = "Detail", id = "", productName = "" } 
);

Add the name-part to your controller and check that it is the right name:

public ActionResult Detail(int id, string productName) 
{ 
    Product product = IProductRepository.Fetch(id); 

    string realTitle = product.Title; // Add encoding here

    if (realTitle != urlTitle) 
    { 
        Response.Status = "301 Moved Permanently"; 
        Response.StatusCode = 301; 
        Response.AddHeader("Location", "/Products/" + product.Id + "/" + realTitle); // Or use the UrlHelper here
        Response.End(); 
    }

    return View(product); 
}

update
The url apparently is broken. This article describes mostly the same functionality: http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx

Thanks to Stu1986C for the comment / new link!