3

我已经找到了几个关于基于角色的身份验证的示例,但这不是身份验证问题。我有三种用户类型,其中一种我希望有一个不同的默认起始页面。Route-config 在用户信息可用之前被初始化。

简而言之:如果角色 A 或角色 B 从下面开始

Controller: Home 
Action: Index

别的:

Controller: Other
Action: OtherIndex

这应该在哪里以及如何实施?

编辑

这应该只在第一次访问站点时发生,其他用户可以转到主页/索引,而不是默认情况下。

编辑

使用 Brad 的建议,我使用他的重定向逻辑创建了一个重定向属性,并将其应用于 Index。然后我为页面创建了另一个动作。这样,如果我确实需要允许访问 HomeIndex,我可以专门为它分配 Home/HomeIndex,任何使用默认路由的东西都可以访问 Home/Index

[RedirectUserFilter]
public ActionResult Index()
{
     return HomeIndex();
}

对于那些需要它的人 - 这是属性

 public class RedirectUserFilterAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {

            if (!HttpContext.Current.User.IsInRole("Role A") 
            && !HttpContext.Current.User.IsInRole("Role B"))
            {
               actionContext.Result = new RedirectToRouteResult(
               new RouteValueDictionary {
                           { "Controller", "OtherController" }, 
                           { "Action", "OtherAction" } });
             }

          }
       }
4

1 回答 1

5
public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (
            !User.IsInRole("Something") &&
            !User.IsInRole("Role B")
        ) return RedirectToAction("OtherIndex");
        // ...
    }
}

也一样OtherController

或者,您可以创建自己的ActionFilter查找常规命名的操作(如IndexRolenameover Index

于 2013-08-27T18:35:32.137 回答