的Controler:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
int userId = WebSecurity.GetUserId(model.UserName);
string roleName = ConfigurationManager.AppSettings["CustomerRole"];
if (!Roles.RoleExists(roleName)){ Roles.CreateRole(roleName); }
Roles.AddUserToRole(model.UserName, roleName);
var customer = new Customer();
customer.UserId = userId;
customer.Name = model.Name;
customer.PrivateEmail = model.PrivateEmail;
_customerRepo.Add(customer);
_customerRepo.SaveChanges(); // Customer, Membership, UserProfile added to db, no problems
TempData["Message"] = "User was registered"; // shows
return RedirectToAction("Index", "Home"); // shows
似乎所有内容都正确保存但部分视图不再看到此用户... _LoginPartial view
@if(Request.IsAuthenticated) {
<text> user: @Html.ActionLink(User.Identity.Name, "Manage", "Account",routeValues: null, htmlAttributes: new { @class = "username", title = "Change Password" })
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
{@Html.AntiForgeryToken()
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>}
</text>
} else {
<ul>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Register", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
答案 0 :(得分:1)
您需要在SaveChanges();
之后调用Login()应该是
WebSecurity.Login(model.UserName,model.Password,false);
更多信息http://www.codeguru.com/csharp/.net/net_asp/mvc/using-simplemembership-in-asp.net-mvc-4.htm