开发者

ASP.Net MVC: Rewriting with routing

I want to map the following URI:

/admin/controller/action/id

to the following:

Controller -> Controller
Action     -> Admin_Action

For example:

/admin/Users/Create

Controller -> Users
Action  -> Admin_Create

/admi开发者_高级运维n/Users/Delete/1

Controller -> Users
Action -> Admin_Delete(1)

Can I achieve that using routing rules?


I think the following route mapping should work ...

 routes.MapRoute("YourRouteName", "admin/controller/action/{id}", new { controller = "Controller", action = "Admin_Action", id = UrlParameter.Optional });


Use this:

routes.MapRoute("Admin",  // Route name
  "admin/{controller}/{action}/{id}",  // URL with parameters
  new { controller = "Controller", action = "Admin_Action", id = UrlParameter.Optional }  // Parameter defaults
);

But if you want you can also do www.example.com/admin/

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

Update

routes.MapRoute(
    "AdminArea",                                              
    "admin/{controller}/{action}/{id}",                     
    new { controller = "Users", action = "Index", id = UrlParameter.Optional } 
);


You can prepend names to actions using a RouteHandler, as I describe in this answer.

If you create a RouteHandler named AdminHandler to prepend "Admin_` to your actions, you can then define your route as follows:

routes.MapRoute("Admin",  // Route name 
    new Route("admin/{controller}/{action}/{id}",  
    new RouteValueDictionary(  
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }),  
        new AdminHandler() 
    ) 
);  

However, I agree with brodie that you should place all admin actions in a separate Area, as it is a better design, and makes security and maintenance easier.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜