url rewriting in mvc4 with razor engine

user3166404 picture user3166404 · Jan 30, 2014 · Viewed 11.4k times · Source

I want to rewrite following url -

http://localhost:99/Product/CategoryLevel?CategoryId=65&ProductName=Vitamins

with

http://localhost:99/Product/Vitamins,

(or)

http://localhost:99/Product/CategoryLevel/Vitamins

(or)

http://localhost:99/Vitamins

(or) how to remove (or) hide the querystring from the url (that was shown to the users)?

I tried using url rewrite module(iis) and asp.net routing and search for the solution in the internet,but i didn't find right solution for this,please suggest any solutions.

Answer

JotaBe picture JotaBe · Jan 30, 2014

You must map this route before all the other route mappings (routes are evaluated in order):

routes.MapRoute(
  name: "Product", // any name meaningful for you is right
  url: "Product/{productName}",
   defaults: new { controller = "Product", action = "CategoryLevel" }
);

This route will catch all the URLS that look like this:

http://myserver/Product/X

whatever X is. If you do so, your action should look like this:

public ActionResult CategoryLevel(string productName)

NOTE: The parameter name must match the segment in the route mapping: productName

So, whenever the user types:

http://myserver/Product/Vitamins

the action CategoryLevel will be executed, and it will receive the productName parameter with the value "Vitamins"

The problem is that if you have an action List which you expect to be invoked like this

http://myserver/Product/List

the route will map it and will invoke the CategoryLevel action with the productName = "List"

To avoid this you can use this route:

routes.MapRoute(
  name: "Product", // any name meaningful for you is right
  url: "ViewProduct/{productName}",
   defaults: new { controller = "Product", action = "CategoryLevel" }
);

Which will be different from the others, and anything will work fine. The URLs specific for this method will look like this:

http://myserver/ViewProduct/TheProductName

and the other routes will work as expected.

By the way: you should have an specific action for the product, for example View, instead of CategoryLevel. So, the route and the action would look like this:

    routes.MapRoute(
        name: "ViewProduct", // any name meaningful for you is right
        url: "ViewProduct/{productName}",
        defaults: new { controller = "Product", action = "View" }
    );

The action, inside the product controller:

public ActionResult View(string productName)

The route is used both for mapping a user typed url to the corresponding action, and for generating URLs by using some of the MVC helpers, like Html.ActionLink or Url.Action. So, if you do something like this:

Url.Action('View', 'Product', new {productName = "Vitamins"} )

you'll get the expected, short URL:

http://myserver/ViewProduct/Vitamins

I.e. the route map it's a two-way map that can map URLs to actions and viceversa.