How to set profile data for new user

时间秒杀一切 提交于 2019-12-05 04:21:41

问题


I have an MVC3 site and I am writing code to register a user. The code does this:

MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

The next thing it does is this:

HttpContext.Profile["FirstNAme"] = model.FirstName;
HttpContext.Profile["LastName"] = model.LastName;

This is where it fails. The error I get is:

This property cannot be set for anonymous users.

I understand why; it is because there is no user logged in or no user specified, so of course I can't set the profile for the user. I am working from page 754 onwards of Pro ASP.NET MVC 3 Framework and this is where I got this code from. I have set this up in the web.config file.

<profile enabled="true" defaultProvider="AspNetSqlProfileProvider">
  <providers>
    <clear/>
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
  </providers>
  <properties>
    <add name="FirstName" type="String"/>
    <add name="LastName" type="String"/>
  </properties>
</profile>

My question is how do I set the first name and last name of the user I am trying to register?


回答1:


Try getting the profile for that user's username by:

ProfileBase profile = ProfileBase.Create(model.UserName);

Yes, create 'gets' the profile for the user you just created, not just creates it (misleading!). Then you can use:

profile["FirstName"] = model.FirstName;
profile["LastName"] = model.LastName;

Don't forget to call profile.Save(); after setting the values



来源:https://stackoverflow.com/questions/8893387/how-to-set-profile-data-for-new-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!