![](/img/trans.png)
[英]What is the best way to customize user authorization when basing user privilege on something other than specific accounts/roles?
[英]What's the best way to direct user to different views by roles?
在我的ASP.NET MVC 5應用程序中,我們有很多用戶角色,例如Admin,ReportUser,ProjectManager和類似的東西。 我希望應用程序根據以下規則在登錄后立即將用戶重定向到視圖:
如果用戶是Admin,則重定向到/ Admin / Index
如果用戶是ReportUser,則重定向到/ Report / Index
如果用戶是ProjectManager,則重定向到/ Project / Index
我已經在web.config中使用AspNetWindowsTokenRoleProvider設置了角色管理器,並在global.asax的MyMvcApplication_PostAuthenticateRequest中設置了用戶角色,效果很好。
但是,我不清楚進行重定向的最佳方法在哪里和什么地方。 在自定義授權屬性類的OnAuthorization方法中? 還是在global.asax的MyMvcApplication_PostAuthenticateRequest方法中?
如果您使用默認的Asp.net身份登錄和模板邏輯,則應具有類似於以下內容的登錄方法:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindAsync(model.Email, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
因此,創建一個新方法:
public async Task<ActionResult> GoHome()
{
if (this.User.IsInRole("Admin"))
{
return Redirect("Action", "Controller");
}
// etc etc
}
然后只需通過更改更新Login方法:
return RedirectToLocal(returnUrl);
至
return Redirect("GoHome");
雙重重定向的原因是身份驗證發生在MVC管道之前,這意味着await SignInAsync(user, model.RememberMe)
不會更改當前用戶上下文,它要求MVC進行重定向才能看到更改。 因此,在下一頁上,它可以讀取角色並正確重定向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.