[英]Defining role-based default routing in .NET MVC
I'm surprised I haven't come across this before, but I'm attempting to find a way to redirect to the default route post-authentication based on a user's role. 令我感到惊讶的是,我之前从未遇到过这种情况,但是我试图根据用户角色找到一种重定向到默认路由后身份验证的方法。
To set up an example, let's say there are two roles, Admin and Tester. 为了举例说明,假设有两个角色,即Admin和Tester。 An Admin's default route should be
admin/index
and the AdminController
shouldn't be accessible to a Tester. 管理员的默认路由应为
admin/index
并且测试人员不能访问AdminController
。 A Tester's default route should be test/index
and the TestController
shouldn't be accessible to Admin. 测试人员的默认路由应为
test/index
并且Admin不能访问TestController
。
I looked into route constraints, but apparently they can only be used to determine whether a route is valid. 我研究了路线约束,但显然,它们只能用于确定路线是否有效。 Then I attempted to try to call
RedirectToAction
after logging in, but that got a bit messy with return URLs and another reason that made it even more of a no-no which I can't remember at the moment. 然后,我尝试尝试在登录后调用
RedirectToAction
,但是返回URL有点混乱,另一个原因使此刻我什至不记得了。
I've landed on the following which I've implemented in my BaseController
, but it's less than optimal to execute this on every controller action: 我已经在
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" }));
}
}
Is there a best practice for handling the default route based on user role? 是否有最佳实践来处理基于用户角色的默认路由?
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.