【问题标题】:Different default routes for different roles不同角色的不同默认路由
【发布时间】:2012-10-28 15:15:39
【问题描述】:

是否可以为不同的用户角色创建不同的默认路由?

例如

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

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

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

        }

上面有普通用户的默认路由,但如果管理员用户登录,则使用管理员路由?

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

MVC 不支持基于角色的路由。您所做的是使用默认控制器检查角色并重定向到该控制器

public ActionResult Index()
    {

        if (User.IsInRole("Supervisor"))
        {
            return RedirectToAction("Index", "InvitationS");
        }
        return View();
    }

http://forums.asp.net/t/1994888.aspx?role+based+routing+asp+net+mvc

【讨论】:

    【解决方案2】:

    使用自定义 RouteConstraint 在 mvc 5 上为我解决了问题。

        public class RoleConstraint : IRouteConstraint
        {
            public bool Match
                (
                    HttpContextBase httpContext,
                    Route route,
                    string parameterName,
                    RouteValueDictionary values,
                    RouteDirection routeDirection
                )
            {
                return httpContext.User.IsInRole(parameterName) ;
            }
        }
    

    RouteConfig.cs

        routes.MapRoute(
            name: "Reader_Home",
            url: "",
            defaults: new { controller = "Reader", action = "Index", id = UrlParameter.Optional },
            constraints: new { reader_role = new RoleConstraint() }
        );
    
        routes.MapRoute(
            name: "Author_Home",
            url: "",
            defaults: new { controller = "Publication", action = "Index", id = UrlParameter.Optional },
            constraints: new { author_role = new RoleConstraint() }
        );
    

    我使用 parameterName(author_role 和 reader_role)作为角色名称来检查是否简化。

    【讨论】:

    • 是否可以验证目标控制器/操作是否需要身份验证?例如,我有一些允许匿名的控制器和操作
    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2016-10-11
    • 2021-04-22
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多