我正在使用 ASP.NET MVC4,我已经设置了一个自定义配置文件类,如这篇关于通用会员提供程序的文章中所述
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;
我知道在数据库级别,配置文件只会将所有相关列保存在同一个表中,我只想在服务层上组织属性。有没有办法做到这一点?