我已创建自己的注册表单并使用Membership类创建用户。

MembershipCreateStatus status;
MembershipUser newUser = Membership.CreateUser(tbxUsername.Text, 
                                               tbxPassword.Text, 
                                               tbxEmail.Text, 
                                               null, null, true, out status);

使用代码创建用户后,我尝试设置一些配置文件属性,如此

Profile.CountryCode = ddlCountry.SelectedValue;
Profile.DisplayName = tbxDisplayName.Text;
Profile.Save();

但是我收到以下异常消息

无法为匿名用户设置此属性。

任何想法为什么我得到这个?

有帮助吗?

解决方案

我认为这是因为您没有先获取配置文件(从DB /无论您使用的是什么)。

您的代码可能如下所示:

ProfileCommon p = Profile.GetProfile(tbxUsername.Text);
p.CountryCode = ddlCountry.SelectedValue;
p.DisplayName = tbxDisplayName.Text;
p.Save();

其他提示

我遇到了同样的错误,那是因为我只设置了authCookie,但没有设置httpcontext用户。看哪:

HttpCookie authCookie = HttpContext.CurrentRequest.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
    //Extract the forms authentication cookie
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

    // If caching roles in userData field then extract
    string[] roles = authTicket.UserData.Split(new char[] { '|' });

    // Create the IIdentity instance
    IIdentity id = new FormsIdentity(authTicket);

    // Create the IPrinciple instance
    IPrincipal principal = new GenericPrincipal(id, roles);

    // Set the context user 
    HttpContext.Current.User = principal;
}

特别感谢这篇文章代码!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top