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

C# 在.NET MVC中定义基于角色的默认路由,c#,asp.net-mvc,C#,Asp.net Mvc,我很惊讶我以前没有遇到过这种情况,但我正试图找到一种方法,根据用户的角色重定向到默认路由后身份验证 为了建立一个示例,假设有两个角色,Admin和Tester。管理员的默认路径应该是Admin/index,测试人员不应该访问AdminController。测试人员的默认路径应该是test/index,管理员不应该访问TestController 我研究了路由约束,但显然它们只能用于确定路由是否有效。然后,我尝试在登录后调用RedirectToAction,但返回的URL有点混乱,另一个原因使它更

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

为了建立一个示例,假设有两个角色,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" }));
    }
}
是否有基于用户角色处理默认路由的最佳实践?

使用Microsoft.AspNet.Identity;
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.
[授权] 公共类AdminController:Controller{ /*在这里做你的事情。如果你的视图实际上与tester视图没有太大区别,并且你只会对tester或viceversa隐藏一些对象,我建议你使用相同的视图,但在控制器内使用不同的方法。实际上,你根本不需要制作AdminController和tester Controller*/ } //您可以在一个控制器中执行此操作,如 [授权(Roles=“Admin”)] 公共行动结果详细信息RADMIN(int id) { var myRole=db.MyModelsAccounts.Find(id);
return View(“Admin”,myRole);//您可以为控制器中的方法使用角色。例如-User.IsInRole(“Tester”)public void methodname(){}这意味着,此方法只能由测试人员访问。因此,请查看此链接-@HappyLee:确定可访问性不是问题所在。此外,我曾尝试实现您链接的解决方案,但它不起作用,然后我被告知路由约束仅用于验证路由有效性。不确定错误通信发生在何处curred,但我知道如何管理可访问性。