开发者

MVC - RegisterRoutes

开发者 https://www.devze.com 2023-04-09 06:14 出处:网络
I would like to rewrite the url from http://localhost:51639/home/index?id=123 to http://localhost:51639/home/product

I would like to rewrite the url from

http://localhost:51639/home/index?id=123

to

http://localhost:51639/home/product

Here is my code in Global.asax.cs

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{reso开发者_开发技巧urce}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

What can I do? Thanks a lot


Important is the order, because MVC searchs first a fit with RouteCollection and return a url.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(null, "home/product/{id}", new {
            controller = "Home", action = "Index",
            id = UrlParameter.Optional}
    );
    routes.MapRoute("Default",  // Route name
            "{controller}/{action}/{id}",   // URL with parameters
            new {
                controller = "Home", action = "Index",
                id = UrlParameter.Optional }    // Parameter defaults
    );
}


If you're using MVC 5, you can use a custom route parameter, i.e. [Route("home/product/{id:int}")]. It's really useful for one off routes, and since you can specify a type in the parameter that's passed, it doesn't conflict with other deep routes you might need.

http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消