定义条件路线

Gor*_*uri 9 asp.net asp.net-mvc-routing asp.net-mvc-3

我一直在寻找类似但没有运气的东西.我想构建一个应用程序,为不同的URL使用不同的控制器.基本的想法是,如果用户以管理员身份登录,他会使用管理控制器,如果用户只是用户,则使用用户控制器.这只是一个例子,基本上我想要一个决定控制器路由所需的函数.

谢谢大家.任何帮助是极大的赞赏.

PS使用此:Admin具有不同的UI和选项,输出捕获,关注分离

cou*_*ben 14

您需要创建RouteConstraint来检查用户的角色,如下所示:

using System;
using System.Web; 
using System.Web.Routing;

namespace Examples.Extensions
{
    public class MustBeAdmin : IRouteConstraint
    {
        public MustBeAdmin()
        { }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
        {
            // return true if user is in Admin role
            return httpContext.User.IsInRole("Admin");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在默认路由之前,为Admin角色声明路由,如下所示:

routes.MapRoute(
    "Admins", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Admin", action = "Index", id = UrlParameter.Optional }, // Parameter default
    new { controller = new MustBeAdmin() }  // our constraint
);
Run Code Online (Sandbox Code Playgroud)

counsellorben

  • 如果用户以普通用户身份登录,那么他/她将被重定向到用户控制器,代码中在哪里提到? (2认同)