我想在注册时获得UserId
[AllowAnonymous]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
//Object reference not set to an instance of an object.
Guid id = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
System.Web.Security.Roles.AddUserToRole(model.UserName, "User");
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
但是发生错误(“对象引用未设置为对象的实例。”)。如何在register方法中获取userId?
感谢。
答案 0 :(得分:5)
FormsAuthentication.SetAuthCookie
对下一个请求进行身份验证,同一请求上的System.Web.Security.Membership.GetUser()
将返回null:
SetAuthCookie方法向其中任何一个添加表单身份验证票证 如果CookiesSupported为false,则为Cookie集合或URL。该 forms-authentication ticket提供表单 - 身份验证信息 到浏览器发出的下一个请求。使用表单身份验证 如果要对a进行身份验证,可以使用SetAuthCookie方法 用户但仍保留对重定向的导航控制权。
Membership.CreateUser
返回创建的用户,因此您应该能够执行此操作:
[AllowAnonymous]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
MembershipUser membershipUser = Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
Guid id = (Guid)membershipUser.ProviderUserKey;
...