asp.net mvc routing question

笑着哭i 提交于 2019-12-05 20:34:00

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
     }
}

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)

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