Mvc 5基于角色的重定向 [英] Mvc 5 role based redirection

查看:72
本文介绍了Mvc 5基于角色的重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一个有3个角色的基本应用程序:



*管理员

*服务员

*捐助者



在项目启动时,用户将被定向到登录/注册视图。如果用户以管理员身份登录,则应将其重定向到具有AdminLayoutPage.cshtml的管理视图。如果捐赠者登录,他应该使用DonorLayoutPage.cshtml重定向到Donor视图。但是我没有得到理想的结果。我已尝试在登录控制器中验证方法:



[HttpPost]

[AllowAnonymous]

[ ValidateAntiForgeryToken]

公共异步任务< actionresult>登录(LoginViewModel模型,字符串returnUrl)

{

if(ModelState.IsValid)

{

var user =等待UserManager.FindAsync(model.UserName,model.Password);

if(user!= null&& User.IsInRole(Admin))

{

等待SignInAsync(user,model.RememberMe);

返回RedirectToLocal(returnUrl);

}

else

{

ModelState.AddModelError(,无效的用户名或密码。);

}

}



//如果我们到目前为止,有些事情失败,重新显示形式

返回查看(模型);

}

I have designed a basic application that has 3 roles:

* Admin
* Clerk
* Donor

On startup of the project the user is directed to the Login/Register view. If a user login as an admin he should be redirect to the admin view that has an AdminLayoutPage.cshtml. If a donor login he should be redirected to the Donor view with DonorLayoutPage.cshtml. However I dont get the desired result. I have tried methods in the login controller to validate:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<actionresult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null && User.IsInRole("Admin"))
{
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);
}

推荐答案

好的,那么如何跟踪谁扮演什么角色?如果您正在使用默认提供程序和数据库,那么此代码应该可以工作,除非用户不在Admin角色中。



我的个人意见是RedirectToAction,它显示了管理员视图而不是RedirectToLocal。这样你就不用担心URL了。



什么是所有该死的Async东西本质上是一个同步操作第一名??
OK, so how are you tracking who is in what role? If you're using the default provider and database then this code should work unless the user is not in the Admin role.

My personal opinion is to RedirectToAction that shows the Admin view instead of RedirectToLocal. That way you don't have to worry about URLs at all.

And what's with all the damn Async stuff on what is, by nature, a synchronous operation in the first place??


这篇关于Mvc 5基于角色的重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆