gpt4 book ai didi

asp.net-mvc - ASP.NET 成员资格 : Custom Profile Inheritance

转载 作者:行者123 更新时间:2023-12-04 04:57:35 25 4
gpt4 key购买 nike

我正在使用 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;

我知道在数据库级别,配置文件只会将所有相关列保存在同一个表中,我只想在服务层上组织属性。有没有办法实现这一目标?

最佳答案

在 ProviderModel 内部是不可能的,但是如果您围绕它构建一个层,则可以实现它。你可以通过几种方式:

  • 将相关信息保存在另一个表中,并在配置文件中保存对该信息的引用。然后,您可以保留一个简单的配置文件类并使用存储库或其他相关类来获取额外信息(可能是具有子类型的基类型)。这将有利于对象组合而不是继承。
  • 保留一个具有所有属性的简单配置文件类。不是直接从 HttpContext 获取配置文件,你可以在它周围构建一个层(如果你愿意的话,工厂),它检查实例并返回不同的类型,这取决于配置文件中的值
  • 关于asp.net-mvc - ASP.NET 成员资格 : Custom Profile Inheritance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16574747/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com