我正在使用ASP.NET MVC4,我已按照此article about universal membership providers
中的说明设置了自定义配置文件类public class CustomProfile : ProfileBase
{
public DateTime? Birthdate
{
get { return this["Birthdate"] as DateTime?; }
set { this["Birthdate"] = value; }
}
public static CustomProfile GetUserProfile(string username)
{
return Create(username) as CustomProfile;
}
public static CustomProfile GetUserProfile()
{
var user = Membership.GetUser();
if (user == null)
return null;
return Create(user.UserName) as CustomProfile;
}
}
我还在web.config上更新了配置文件定义的条目:
<profile defaultProvider="DefaultProfileProvider" inherits="MembershipTestsV3.Models.CustomProfile">
<providers>
<add name="DefaultProfileProvider"
type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"
applicationName="MyAppName" />
</providers>
</profile>
这意味着我可以随时实例化我的自定义配置文件对象:
var customProfile = HttpContext.Profile as CustomProfile;
现在,我希望从这个基础继承许多类型的配置文件;例如AdminUserProfile或SupervisorProfile:
public class SupervisorProfile : CustomProfile
{
public string Department
{
get { return this["Department"] as string; }
set { this["Department"] = value; }
}
}
但是,每次我尝试转换对象时,我都会得到一个空引用异常:
var customProfile = HttpContext.Profile as SupervisorProfile;
我知道在数据库级别,配置文件只会将所有相关列保存在同一个表中,我只想在服务层上组织属性。有没有办法实现这个目标?
答案 0 :(得分:3)
在ProviderModel中是不可能的,但如果围绕它构建一个层,就可以实现它。你可以采取多种方式: