简体   繁体   中英

Asp.Net 4.6 How to add a route prefix to controllers

I need to add one 'pathname' prior to some controllers in order to clarify their purpose.

For example, currently:

/news/create , /news/edit , /event/create , /event/edit ,

I wish their router could be

/request/news/create , /request/news/edit , /request/event/create , /request/event/edit

I tried to add the following code in RouteConfig.cs

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

One of controllers EventController.cs

public class EventController : Controller{

        [HttpPost]
        public ActionResult Edit(int id, Events eventModel){
          //code
        }

        [HttpPost]
        public ActionResult Create(Events eventModel){
          //code
        }
}

Here I meet a problem:

/request/event/create 404 error

/request/event/edit/1 works!

/event/create works!

/event/edit/1 works!

So, my question is why /request/event/create doesn't work and how to fix that?

As far as I know, adding [Route("request/event/create")] above Create action could make it work.

---------Update--------

RouteConfig.cs

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

            routes.MapMvcAttributeRoutes();

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


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

Order of registered routes is important. Move more specific routes to before general routes

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

        routes.MapMvcAttributeRoutes();

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

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



    }
}

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