Hide one controller name from mvc url, show other

2019-05-21 07:46发布

I have two controllers, HomeController and ResourcesController. I want to hide the Home/ from the url when action on HomeController is requested, but for ResourcesController (or any other controlelr) I want to keep the controller name in url. E.g. /Home/Products will be /Produtcs, but /Resources/Banana should stay /Resources/Banana

These are my routes:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "SpecificRoute",
        url: "{action}/{id}", 
        defaults: new { controller = "Home", action = "Home", id = UrlParameter.Optional });

routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Home", id = UrlParameter.Optional }
);

It works as expected for home controller but for resources controller I get "404... The resource cannot be found"

1条回答
戒情不戒烟
2楼-- · 2019-05-21 08:19

One possible way is you can map all the home page actions within the global.asax file. See the example code below.

e.g.

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

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

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
查看更多
登录 后发表回答