IIS8 Express上的SqlRoleProvider

时间:2012-10-22 12:16:34

标签: asp.net iis-express iis-8 sqlroleprovider

我的Web应用程序(WCF服务)使用SqlRoleProvider,可以在 Visual Studio Development Server 上正常运行。将其切换为 IIS8 Express 会导致它抛出NullReferenceException但是:

Roles.IsUserInRole(username, role) // neither of them actually null

我无法在the IsUserInRole method documentation中找到此异常的提示。切换回Visual Studio开发服务器使其工作。这个例外的原因是什么,我该怎样才能正确修复?项目的目标框架 .NET Framework 4

这是配置的连接字符串:

<add name="ConnectionString"
      connectionString="Data Source=.\sqlexpress;Initial Catalog=DevWeb;Integrated Security=True"
      providerName="System.Data.SqlClient" />

这是roleManager/providers节点:

<clear />
<add connectionStringName="ConnectionString" applicationName="MyApp" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/>

3 个答案:

答案 0 :(得分:4)

弗拉基米尔说的是真的,但实际上并没有解释发生了什么。抛出NullReferenceException的是IsUserInRole和GetRolesForUser中的EtwTrace代码。 Roles类中的其他所有内容都说明HttpContext.Current可以为null。我在http://referencesource.microsoft.com/netframework.aspx

的Microsoft参考源中找到了“NET,Version 4.5”

在我尝试过的每个其他测试环境中,跟踪级别都不足以触发NullReferenceException。只有当我在安装Visual Studio 2013之后使用IIS Express 8时才能看到问题并且只能在IIS Express中使用。

你能做些什么?

一种选择是为WCF启用“ASP.Net兼容模式”。 首先,在web.config中,将属性aspNetCompatibilityEnabled =“true”添加到节点&lt; configuration&gt;&lt; system.serviceModel&gt;&lt; serviceHostingEnvironment&gt;。然后通过将属性[System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]添加到类定义中来选择服务类进入行为。启用此功能后,将填充HttpContext.Current当你从Roles类请求角色时,假设你没有像弗拉基米尔那样提到后台线程(在这种情况下你需要先修补HttpContext.Current)。您可以在http://blogs.msdn.com/b/wenlong/archive/2006/01/23/516041.aspx了解有关WCF的ASP.NET兼容模式的更多信息。

另一种选择是绕过这两种方法的Roles类。而不是调用Roles.IsUserInRole,而是调用Roles.Provider.IsUserInRole。而不是调用Roles.GetRolesForUser,调用Roles.Provider.GetRolesForUser。每种方法都有相同的重载。您丢失了跟踪停止和本地角色缓存,但是您绕过了空引用异常。

答案 1 :(得分:1)

如果你在不同的线程中调用Roles.IsUserInRole,那么你应该检查HttpContext。在这种情况下将是空的。因此,对于修复,您应该将HttpContext从主线程复制到子线程。

        var context = HttpContext.Current;
        Thread thread = new Thread(delegate() {
            if (HttpContext.Current == null)
                HttpContext.Current = context;
        });

        thread.Start();

答案 2 :(得分:0)

相当确定您的问题将与数据库以及访问它的帐户的权限有关。尝试将您的IIS帐户添加到sa priv,并查看问题是否已解决。如果确实如此,则表示您缺少权限。

相关问题