无法获取Application_Start中的个人资料数据



在Application_Start 中的某个时刻,我有以下代码

MembershipUserCollection users = Membership.GetAllUsers();
foreach (MembershipUser u in users)
{
    ProfileBase profile = ProfileBase.Create(u.UserName, false);
    if (profile["Index"] != null)
    {
        // Some code
    }
}

问题是,当我尝试访问配置文件属性时,我会得到"请求在此上下文中不可用"httpException。我尝试过使用个人资料。GetPropertyValue,但也没有运气。

为什么配置文件需要请求对象,以及如何使其工作?

编辑:

我查看了.NET代码,发现在某个时刻调用了SqlProfileProvider.GetPropertyValuesFromDatabase(string userName, SettingsPropertyValueCollection svc),其中包含以下代码串:

if (!current.Request.IsAuthenticated)

显然,如果不在请求上下文中,这将永远不会起作用。奥努尔的回答中描述的解决方法会很好。

显然您正在尝试访问请求对象,这在您的情况下是不可能的。

请查看以下链接,并在可能的情况下应用其中一个解决方案。http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart

如果你提供更多的信息,我们可以找到另一种方法。

您可以通过查询aspnet_Profiles表并解析字符串来获得"字符串值"属性。

SELECT [UserName]
  ,[PropertyNames]
  ,[PropertyValuesString]
FROM [aspnet_Profile]
LEFT JOIN [aspnet_Users] on [aspnet_Users].UserId = [aspnet_Profile].UserId

PropertyValuesString可以通过一些代码进行解析。此链接应详细解释格式https://msdn.microsoft.com/en-us/library/aa478953.aspx#persistence_format.

最新更新