gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 在创建用户时获取 userId?

转载 作者:行者123 更新时间:2023-12-03 17:48:57 25 4
gpt4 key购买 nike

注册时想获取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?

谢谢。

最佳答案

FormsAuthentication.SetAuthCookie验证下一个 请求,System.Web.Security.Membership.GetUser() 对同一请求将返回 null:

The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection or the URL if CookiesSupported is false. The forms-authentication ticket supplies forms-authentication information to the next request made by the browser. With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.

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;
...

关于asp.net-mvc - ASP.NET MVC 在创建用户时获取 userId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10258461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com