Rewriting URLs in mvc4 with a shaving engine

I want to rewrite the following url -

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

from

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

(or)

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

(or)

http://localhost:99/Vitamins

(or) how to remove (or) hide the query string from the URL (which was shown to users)?

I tried to use url rewrite module (iis) and asp.net routing and find a solution on the Internet, but I did not find a suitable solution for this, please suggest any solutions.

+4
source share
3 answers

You must map this route before all 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" }
);

URL-, :

http://myserver/Product/X

X. , :

public ActionResult CategoryLevel(string productName)

. : productName

, , :

http://myserver/Product/Vitamins

CategoryLevel, productName "Vitamins"

, List,

http://myserver/Product/List

CategoryLevel productName= "List"

, :

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

, . URL-, , :

http://myserver/ViewProduct/TheProductName

, .

: , View, CategoryLevel. , :

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

:

public ActionResult View(string productName)

URL- , URL- MVC, Html.ActionLink Url.Action. , - :

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

URL-:

http://myserver/ViewProduct/Vitamins

.. , URL- .

+8

You need to edit AppData > RouteConfig.cs

add the following lines of code (lower by default)

        routes.MapRoute(
            name: "[Choose a name]",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Product", action = "CategoryLevel", id = UrlParameter.Optional }
        );

And your Controller action should be next

public ActionResult CategoryLevel(string ID)
{
}
-2
source

Source: https://habr.com/ru/post/1524443/


All Articles