user.Roles
将提取用户所属的角色列表。根据您的需要,你可以这样做下面根据我们的讨论
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Username);
if (user != null)
{
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
if(await UserManager.IsInRoleAsync(user.Id,"Admin")) //<= Checking Role and redirecting accordingly.
return RedirectToAction("Index", "Admin");
else
return RedirectToAction("Index", "User");
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
,如果你想获取所有从数据库中你需要做以下
角色如下ApplicationRoleManager
类添加到您的IdentityConfig.cs
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
: base(store)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
var manager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
return manager;
}
}
分配RoleManager到Owin语境,所以下面添加到starup.auth.cs
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
//other code here
}
在AccountController.cs添加属性
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
传递给它的构造
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,ApplicationRoleManager roleManager)
{
UserManager = userManager;
SignInManager = signInManager;
RoleManager = roleManager;
}
一旦你这个做,你可以通过使用 VAR角色= RoleManager.Roles获取所有的角色列表;
您可以根据您的要求使用它。
通过查看[user.Roles](https://msdn.microsoft.com/en-us/library/mt151766(v = vs.108).aspx#P:Microsoft.AspNet.Identity.EntityFramework.IdentityUser '4.Roles)? – Michael
你在做什么,你为什么在用户登录时试图阅读用户角色? – Emil