Question

I've created my own signup form and creating the user using the Membership class.

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

After the user is created using the code about, I try to set some profile properties like so

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

However I get the following exception message

This property cannot be set for anonymous users.

Any ideas why im getting this?

Was it helpful?

Solution

I Think this is beacuse you didn't fetched the profile first (from DB/Whatever you are using).

you code might look like the following:

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

OTHER TIPS

I ran into the same error and it was because I was only setting the authCookie, but not setting the httpcontext user. Behold:

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

Special thanks to this post for the code!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top