【问题标题】:Accessing asp.net Profiles from App_Code从 App_Code 访问 asp.net 配置文件
【发布时间】:2009-10-20 04:58:17
【问题描述】:
我正在创建一个从中派生特定页面的基类。也就是说,它们不是从 System.Web.UI.Page 继承我的页面,而是从 MyPage 继承(而后者又从 System.Web.UI.Page 继承)。
但是,我似乎无法访问 Profile 属性。尽管它们都继承自 Page,但我只能在实际页面级别访问 Profile 属性。
我确定这只是我对页面生命周期的误解,但是有没有办法从 App_Code 中定义的自定义类访问 Profile?
【问题讨论】:
标签:
asp.net
inheritance
asp.net-profiles
app-code
【解决方案1】:
当您在页面中时,您可以使用 ProfileCommon 类来访问配置文件。 profilecommon 类是由 asp.net 在编译 Web 项目期间根据您的 web.config 配置文件设置自动生成的。
如果您想使用 app_code 文件夹中的配置文件,则必须使用 profilebase 类。页面中可用的 Profilecommon 也派生自此类。
Profilebase 可以这样访问
HttpContext.Profile or HttpContext.Current.Profile
要读取配置文件值,您需要执行以下操作
HttpContext.Profile.GetPropertyValue("propertyName");
要将值写入您需要写入的配置文件
HttpContext.Profile.SetPropertyValue("propertyName", "propertyValue");
【解决方案2】:
您可以通过将其强制转换为 ProfileCommon 类型来访问强类型配置文件属性,如下所示:
Dim Profile as ProfileCommon = CType(HttpContext.Current.Profile, ProfileCommon)
Profile.MyProperty1 = "Testing"
Profile.MyProperty2 = "Cool"
【解决方案3】:
如果您想检索另一个用户(而不是活动用户)的配置文件属性值,则此方法有效:
Dim theUser As MembershipUser = Membership.GetUser(userID)
Dim theUserProfile As ProfileBase = ProfileBase.Create(theUser.UserName, True)
Dim theProperty As String = theUserProfile.GetPropertyValue("Property")
您可以在后面的代码中使用 ProfileCommon,但它在 App_Code 中不可用。
参考:MSDN