在.NET MVC中定义基于角色的默认路由

时间:2015-03-30 20:58:34

标签: c# asp.net-mvc

我很惊讶我以前没遇到过这种情况,但我试图找到一种方法,根据用户的角色重定向到身份验证后的默认路由。

要设置示例,假设有两个角色,Admin和Tester。管理员的默认路由应为admin/index,并且测试人员无法访问AdminController。测试人员的默认路由应为test/index,管理员不应访问TestController

我研究了路线约束,但显然它们只能用于确定路线是否有效。然后我尝试在登录后尝试调用RedirectToAction,但是返回URL有点混乱,另一个原因使得它更像是一个我从此不记得的禁忌。

我已经在我的BaseController中实现了以下内容,但是在每个控制器操作上执行此操作并不是最佳的:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.Controller.GetType() == typeof(TestController) && 
        User.IsInRole("Admin"))
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Admin", action = "Index" }));
    else if (filterContext.Controller.GetType() == typeof(AdminController) && 
        User.IsInRole("Tester"))
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Test", action = "Index" }));
    } 
    else
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
    }
}

是否有基于用户角色处理默认路由的最佳做法?

1 个答案:

答案 0 :(得分:0)

using Microsoft.AspNet.Identity;



[Authrorize]
public class AdminController : Controller{

 /* do your stuff in here. If your View is not actually a big difference from the tester view and you will only Hide some objects from the tester or viceversa, I suggest you use the same View but make a different methods inside the Controller. Actually you don't need to make AdminController and Tester Controller at all. */



}


// you can just do this in one Controller like

[Authorize(Roles="Admin")]
public ActionResult DetailsForAdmin(int id)
{
    var myRole = db.MyModelsAccounts.Find(id);
    return View("Admin", myRole);  //<- Admin returning View
}


[Authorize(Roles="Test")]
public ActionResult DetailsForTester

I think you get the Idea.