[英]Defining role-based default routing in .NET MVC
令我感到惊讶的是,我之前从未遇到过这种情况,但是我试图根据用户角色找到一种重定向到默认路由后身份验证的方法。
为了举例说明,假设有两个角色,即Admin和Tester。 管理员的默认路由应为admin/index
并且测试人员不能访问AdminController
。 测试人员的默认路由应为test/index
并且Admin不能访问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" }));
}
}
是否有最佳实践来处理基于用户角色的默认路由?
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.