我是MVC的新手,我正在尝试构建一个小型测试应用程序,以便清楚地了解SimpleMembershipProvider如何在MVC 4中工作。我创建了两个角色 - 学生和教师。我只有一个用户分配了教师角色(在Configuration.cs中硬编码),谁将创建学生,在创建新学生时,教师还将为该学生生成用户ID和密码。然后新创建的学生将使用教师创建的用户标识和密码登录应用程序,并执行某些任务。 问题是每当具有教师角色的用户创建学生时,具有教师角色的当前登录用户将被注销并且新创建的学生将登录。我所做的是,我没有为userid保留任何字段和学生模型中的密码。我使用部分视图绑定到 RegisterModel (来自AccountModels),以便在创建新学生时生成用户名和密码的字段。我在 UserProfile 模型中保留了 StudentID 。 这是我的代码,如下所示,以进一步说明。
学生模特
public class Student
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Date of Birth")]
public string DateOfBirth { get; set; }
public Gender Gender { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
UserProfile模型
public class UserProfile
{
public int UserId { get; set; }
public string UserName { get; set; }
public int StudentId { get; set; }
}
这是来自我创建角色的Configuration.cs和具有教师角色的用户
private void SeedMemebership()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection1",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
if (!roles.RoleExists("Teacher"))
{
roles.CreateRole("Teacher");
}
if (!roles.RoleExists("Student"))
{
roles.CreateRole("Student");
}
if (membership.GetUser("UserFoo", false) == null)
{
membership.CreateUserAndAccount("UserFoo", "Password");
}
if (!roles.GetRolesForUser("UserFoo").Contains("Teacher"))
{
roles.AddUsersToRoles(new[] { "UserFoo" }, new[] { "Teacher" });
}
}
创建学生的控制器操作 -
//
// GET: /Student/Create
[Authorize(Roles = "Teacher", Users = "UserFoo")]
public ActionResult Create()
{
return View();
}
//
// POST: /Student/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Student student, RegisterModel model)
{
if (ModelState.IsValid)
{
try
{
db.Students.Add(student);
db.SaveChanges();
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { StudentId = student.Id });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Student");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
return View(student);
}
对应的观点 -
@model TestApp.Models.Student
@{
ViewBag.Title = "Create";
}
<script type="text/javascript" src="~/Scripts/MyCustom.js"></script>
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Gender, new SelectList(Enum.GetValues(typeof(TestApp.Models.Gender))))
@Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="float-right-top">
@Html.Partial("_PartialRegisterStudent")
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
部分视图“_PartialRegisterStudent.cshtml
@model TestApp.Models.RegisterModel
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
如果没有登录用户退出应用程序,创建具有教师角色的学生的最佳方法是什么?我想过使用继承(Parent - UserProfile,Child-Student)以及学生模型和userprofile模型之间的一对一关系,但是无法弄清楚如何使它工作。代码样本将非常感谢!
P.S。如果这篇文章有点冗长,请为我注册。谢谢。
答案 0 :(得分:3)
只需在“创建操作”中删除以下行,它就可以正常工作。
WebSecurity.Login(model.UserName, model.Password);