注册 _LoginPartial if(Request.IsAuthenticated)

Register _LoginPartial if(Request.IsAuthenticated)

我在这个问题上走投无路了。我是 MVC 的新手,我看到类似的问题出现在 SO 上,但这没有帮助。我基本上是在尝试设置注册操作,一旦用户注册,_LoginPartial 视图应指示用户已通过身份验证。从我阅读的各种帖子和文章中,我相信我缺少将此用户存储到 cookie 的元素,但我不知道如何实现这一点。我将不胜感激任何提示。

控制器:

[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 

似乎所有内容都已正确保存,但部分视图不再显示该用户... _登录部分查看

@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>
}   

您需要在 SaveChanges() 之后调用 Login();

应该是这样的

WebSecurity.Login(model.UserName, model.Password, 假);

更多信息http://www.codeguru.com/csharp/.net/net_asp/mvc/using-simplemembership-in-asp.net-mvc-4.htm