Sitecore asp.net Edit Custom User Profile Properties

1.6k Views Asked by At

I have a field on a user profile that corresponds to an id in another system. I want to set this when a user visits an activation link. After registering the user in the other system, I add a role and set their membership approval to true. I was getting an error saying that I cannot set the property of an anonymous user so I moved where I was assigning the id after the role/activation piece however I still got the same error.

private bool SetCustomId(string username, Guid id)
{

    var userProfile = ((User)User.FromName(username, AccountType.User)).Profile;
    userProfile.SetCustomProperty("MyIdField", id.ToString());
    userProfile.Save();//error thrown here
}

User profile is what I would expect and when I moved it after the piece that assigned the user a role, they did have the role I expected them to.

Here's the actual exception: This property cannot be set for anonymous users.

3

There are 3 best solutions below

2
On BEST ANSWER

Try User.FromName(username, true) instead. The boolean parameter tells it to treat the user as authenticated.

0
On

You need to initialize the user, try the following code:

userProfile.Initialize(username, true);
0
On

Try this:

private bool SetCustomId(string username, Guid id)
{
    using(new Sitecore.Security.Accounts.UserSwitcher(Sitecore.Security.Accounts.User.FromName(username,false));)
    {
        var userProfile = ((User)User.FromName(username, AccountType.User)).Profile;
        userProfile.SetCustomProperty("MyIdField", id.ToString());
        userProfile.Save();
    }

}