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