需求
问题很简单, 希望用户注册登陆之后可以立即在其profile里面添加一个字符串信息: SubCompany.
配置
为了使用profile, 首先要在web.config中进行配置:
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="subCompany" type="String" allowAnonymous="true" />
</properties>
</profile>
提交信息
此时cookie, 也就是formsauthentication的ticket已经成功设置了, 不过 此时 的User.Identity.IsAuthenticated 仍然是false ,这是因为创建的cookie还在客户端上, 需要下一次的http提交才能到达服务器, 系统才能辨识身份,此时的profile仍然是匿名用户的(如果允许匿名用户有profile的话), 这里也谈到这个问题, 当然redirecttoAction一次之后便可以识别了.
所以很容易想到的一个直接方法是redirect到另一个action, 把subCompany的值传过去, 在其中负责profile的信息的更改.不过一般注册成功登录后会自动进行跳转到之前的操作页面, 也就是还要继续跳到业务逻辑需要的地方, 无形中比不使用profile多了一次redirect.
当然我们想要直接立即设置Profile.subCompany也可以, 这取决于是否基于匿名的profile, 就是没有登录也可以存储一些信息在cookie, 这需要在web.config中进行设置:
<anonymousIdentification enabled="true"/>
用户迁移
在设置了匿名身份的情况下, 实际上我们需要把匿名用户的信息迁移到注册用户profile里面去, asp.net给我们提供了一个事件, 来进行匿名用户到注册用户的迁移 .更多资料 http://www.52mvc.com/net/list.aspx
在global.asax.cs中添加事件处理函数, 可在第一次跳转之后自动触发:
protected void Profile_MigrateAnonymous(Object sender, ProfileMigrateEventArgs pe){
var anonymousProfile = CustomProfile.GetProfile(pe.AnonymousID); //取之前的匿名ID
var nowProfile = CustomProfile.GetProfile();//取当前的profile
nowProfile.SubComanyName = anonymousProfile.SubComanyName; //赋值即可
// 删除匿名用户的profile 和其cookie
ProfileManager.DeleteProfile(pe.AnonymousID);
AnonymousIdentificationModule.ClearAnonymousIdentifier();
// 删除匿名用户
Membership.DeleteUser(pe.AnonymousID, true);
}
所以登陆后立即设置profile 信息的位置应该在global.asax中. CustomProfile是一个自定义的类, 下面将会介绍它.
自定义Profile类
如果没有打开匿名身份profile, 那么简单一些, 只要直接获取username对应的profile修改,保存即可, 未跳转之前这涉及到获取其他用户的profile, 因为未跳转之前目前仍是匿名身份, 是不能通过httpcontext.profile来获得的.
不过ASP.NET MVC2比较烦人, 其仍然没有profile.GetProfile(string)这样的函数, 也不会自动生成ProfileCommon这样的辅助类, 带来两个问题是: 1 不能方便的获取其他用户的profile. 2, profile中的属性没有强类型的支持, 不过这2个问题可以通过手动来解决:
首先自己写一个profile类:
public class CustomProfile : ProfileBase{
public virtual string SubComanyName{
get { return ((string)(this.GetPropertyValue("subCompany"))); }
set { this.SetPropertyValue("subCompany", value); }
}
public static CustomProfile GetProfile(){
return (CustomProfile) HttpContext.Current.Profile;
}
public static CustomProfile GetProfile(string userName){
return (CustomProfile) Create(userName);
}
}
其实可以看出, ProfileBase.Create(string) 并非新建, 实则就是load入其他用户的profile, 不过名字起得吓点人罢了. 所以也可以不用自定义这个类, 用基本的api进行profile的操作, 只是稍微有点罗嗦.
然后web.config,添加粗体配置:
<profile inherits="ForeignBussinessManager.Models.CustomProfile">
...
</profile>