注册_LoginPartial if(Request.IsAuthenticated)

时间:2015-05-14 21:00:11

标签: asp.net-mvc simplemembership

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

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

1 个答案:

答案 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

相关问题