asp.net mvc routing question

烈酒焚心 提交于 2019-12-07 18:35:34

问题


the default routing works fine

mysite.com/home/about

and i even see how to customize it to make it shorter

so i can say:

mysite.com/edit/1 instead of mysite.com/home/edit/1

but how can i make it longer to handle url like the following

mysite.com/admin/user/1 // works

mysite.com/admin/user/details // does not work

mysite.com/admin/question/create // does not work

i cant just treat the id as an action? i need a custom route?

do i need to create new controllers for each table or can i route them all through the Admin controller

thanks a lot


回答1:


As has been mentioned already, probably your best bet would be to use the new Areas feature

You can achieve this type of routing without Areas, but as the number of controllers gets large the maintainability of your site will diminish. Essentially what you do is to hard-code the controller name into the Route definition which means that you have to add new route mappings for each new Admin controller. Here's a few examples of how you might want to set up your routes without Areas.

routes.MapRoute("AdminQuestions", // Route name
                "admin/question/{action}/{id}", // URL with parameters
                new { controller = "AdminQuestion", action = "Index" } // Parameter defaults
    );

routes.MapRoute("AdminUsers", // Route name
                "admin/user/{action}/{id}", // URL with parameters
                new { controller = "AdminUser", action = "Index" } // Parameter defaults
    );

Alternatively you could route everything through the Admin controller, but it would quickly become very messy with your controller actions performing multiple roles.

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

With your AdminController action(s) looking like:

public virtual ActionResult Create(string type, int id)
{
    switch (type)
    {
        case 'question':
            // switch/case is code smell
            break;
        case 'user':
            // switch/case is code smell
            break;
        // etc
     }
}



回答2:


Adding routes to global.asax is fairly straight forward. Put the more specific routes above the more general routes. The most typical pattern is controller/action/parameter/parameter... If you need something more complex, you may want to look at MVC Areas.In you example above "mysite.com/admin/user/details" is looking for a controller named "admin" and an action named "user", with everything after that being parameter on the action method (assuming a typical route setup)



来源:https://stackoverflow.com/questions/3409196/asp-net-mvc-routing-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!