我想把身份角色引入我的登录页面。用户在输入用户名和密码后应该选择一个角色的下拉列表(超级用户-管理员-用户)。这怎么会发生?
创建一个类来管理角色,类似于ApplicationRoleManager
public class ApplicationRoleManager : RoleManager<IdentityRole, string>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<ApplicationDbContext>()));
}
}
然后您需要在owin启动时创建ApplicationRoleManager的实例。在Owin启动时,在ConfigureAuth方法中添加以下代码。应用程序启动>>启动.Auth.cs
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
现在,您已经设置好了管理角色的所有设置。确保已将角色添加到"AspNetRoles"表中
然后,您可以在登录(获取)操作中检索如下角色
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
var roles = roleManager.Roles.ToList();
var list = new SelectList(roles, "Id", "Name");
ViewBag.Roles = list;
ViewBag.ReturnUrl = returnUrl;
return View();
}
然后,您可以在"登录"视图中获取角色。之后,用角色填充下拉列表。你的rasor脚本如下所示。
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label id="RoleDdlLabel" class="col-md-2 control-label">Select Role</label>
<div class="col-md-10">
@Html.DropDownList("RoleList", ViewBag.Roles as SelectList)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
@Html.ActionLink("Register as a new user", "Register")
</p>
@* Enable this once you have account confirmation enabled for password reset functionality
<p>
@Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>*@
}
我希望您可以通过将所选角色与其他模型值一起发布来完成保存部分。您可以更改LoginViewModel以包含角色。
希望这能有所帮助。