简体   繁体   中英

custom Routing from controller level in MVC5?

I am trying to defined custom routing in MVC5 like below. But when I call http://company.com/protected/Myaccount is not working. What I am doing wrong.

and also how should defined default load with http://company.com/protected . Now it is loading http://company.com/

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Protected",
                url: "protected/{controller}/{action}/{id}",
                defaults: new { controller = "MyAccount", action = "Index", id = UrlParameter.Optional });

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

    [RoutePrefix("Protected")]
    [Route("{action=index}")]
    public class MyAccountController : Controller
    {
        // GET: MyAccount
        public ActionResult Index()
        {
            ...
        }
    }

Edit: I forgot the second part of your question.

[RoutePrefix("Protected")]
public class MyAccountController : Controller
{
    [Route("Index")] //Route: /Protected/Index
    [Route("")] //Route : /Protected
    [Route("~/")] //Route : /
    public ActionResult Index()
    {
        return View();
    }
}

With [RoutePrefix] you change the access to your controller, with [Route] you can change your access to your action (ex:parameter and order) and defined default for the controller and your app.

In this case, i delete the "Protected" route on RegisterRoute because it's not used. The RouteAttributes is another solution

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

        routes.MapMvcAttributeRoutes();

        //routes.MapRoute(
        //    name: "Protected",
        //    url: "Protected/{Controller}/{action}/{id}",
        //    defaults: new { controller = "MyAccount", action = "Index", id = UrlParameter.Optional }
        //);

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

In fact, attributes routing is another way to define routing, it's more flexible.

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