简体   繁体   中英

How to specify route options to specific controllers in ASP.NET MVC 5

I would like to suppress the controller from the route, and it worked fine using this:

         routes.MapRoute(
            name: "HomePages",
            url: "{action}",
            defaults: new { controller = "Home", action = "Index" }
            );

The problem is when doing the same for a different controller like "Account", the first option only will take effect :

            routes.MapRoute(
     name: "LoginRoute",
     url: "{action}",
     defaults: new { controller = "Account", action = "Login" }
     );

My objective is to hide the controller from the route, so i can directly access mysite.com/login and mysite.com/index, how to achieve that when login is under Account controller and index is under Home controller?

How to specify the second option for the Account actions, and keep the first for the Home actions?

Have you thought about using the Routing attributes eg:

[Route("{getId:int}")]
public ActionResult Show(int getId) { ... }

you can use this in conjunction with the old way of routing. You do need to explicitly set this functionality in your config:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapMvcAttributeRoutes();
    }
}

I have found the routing Attributes makes it very easy to set good routes on my controller methods. This also bleeds into web api and RESTFul stuff as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM