Roles.GetRolesForUser();在 MVC 4 中似乎不起作用

Posted

技术标签:

【中文标题】Roles.GetRolesForUser();在 MVC 4 中似乎不起作用【英文标题】:Roles.GetRolesForUser(); does not seem to work in MVC 4 【发布时间】:2012-08-23 13:26:39 【问题描述】:

我正在尝试使用 VS2012 中提供的 Internet 模板创建一个新的 MVC 4 Internet 站点。我能够为该站点注册用户并成功登录和注销。我可以看到 SimpleMembership 创建了 5 个表(UserProfile、webpages_Membership、webpages_OAuthMembership、webpages_Roles、webpages_UsersInRoles),并且我通过该站点创建的登录名已被放入正确的位置(无论如何我都希望它们正确!)

我遇到的问题是用户的角色。首先,我似乎无法使用旧的 ASP.NET 配置页面 - 它需要永远加载,然后当它最终加载时,当您单击安全链接时会出现此错误:

您选择的数据存储存在问题。这可能是由无效的服务器名称或凭据或权限不足引起的。它也可能是由于未启用角色管理器功能造成的。单击下面的按钮可重定向到您可以选择新数据存储的页面。

以下消息可能有助于诊断问题:无法连接到 SQL Server 数据库。

当您尝试进行提供程序配置时出现此错误

无法建立与数据库的连接。 如果尚未创建 SQL Server 数据库,请退出网站管理工具,使用 aspnet_regsql 命令行实用程序创建和配置数据库,然后返回此工具设置提供程序。

我尝试运行 aspnet_regsql,它在我注册第一个用户时网站已经创建的新成员表旁边创建了旧样式的成员表。

为了解决创建角色的问题,我自己将一个角色放入数据库中,并将一个用户放入该角色中。现在运行该站点,我也无法使用 Roles.GetRolesForUser(),因为它在调试时也显示“无法连接到 SQL Server 数据库”(并且 YOD 给出了空引用异常)。

我注意到在 web.config 中不再有以前存在的关于成员资格/角色提供者等的部分(例如,如果您制作 MVC 3 互联网应用程序)

我这几天一直在寻找答案,谁能解释一下我可能做错了什么?

这是我的 web.config(删除了连接字符串)

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
      <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
      <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
      <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" />
      <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" />
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=EnvoyBilling;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
    <add name="EnvoyBillingContext" connectionString="xxx" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusivejavascriptEnabled" value="true" />
    <add key="enableSimpleMembership" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <legacyHMACWarning enabled="0" />
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <system.net>
    <defaultProxy enabled="true" />
    <settings>
      <!-- This setting causes .NET to check certificate revocation lists (CRL) 
                 before trusting HTTPS certificates.  But this setting tends to not 
                 be allowed in shared hosting environments. -->
      <!--<servicePointManager checkCertificateRevocationList="true"/>-->
    </settings>
  </system.net>
  <dotNetOpenAuth>
    <messaging>
      <untrustedWebRequest>
        <whitelistHosts>
          <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
          <!--<add name="localhost" />-->
        </whitelistHosts>
      </untrustedWebRequest>
    </messaging>
    <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
    <reporting enabled="true" />
    <openid>
      <relyingParty>
        <security requireSsl="false">
          <!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. -->
          <!--<trustedProviders rejectAssertionsFromUntrustedProviders="true">
                        <add endpoint="https://www.google.com/accounts/o8/ud" />
                    </trustedProviders>-->
        </security>
        <behaviors>
          <!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                         with OPs that use Attribute Exchange (in various formats). -->
          <add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" />
        </behaviors>
      </relyingParty>
    </openid>
  </dotNetOpenAuth>
  <uri>
    <!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
             which is necessary for OpenID urls with unicode characters in the domain/host name.
             It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
    <idn enabled="All" />
    <iriParsing enabled="true" />
  </uri>
</configuration>

【问题讨论】:

你能发布你的 web.config 吗? 嗨@Mark,我已经添加了web.config(减去connectionString详细信息) - 我希望它可以帮助你找出我的问题! 【参考方案1】:

我刚刚找到了一个post by Jon Galloway,它谈到了这个确切的情况。他昨天才发的!!!

【讨论】:

【参考方案2】:

您应该在 web.config 中设置成员资格和角色提供者。

  <system.web>
    <roleManager enabled="true">
        <providers>
            <clear/>
            <add name="AspNetSqlRoleProvider" connectionStringName="MyAspNetDB"
                applicationName="/SampleRolesApp"
                type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </providers>
    </roleManager>
    <membership>
        <providers>
            <clear/>
            <add name="AspNetSqlMembershipProvider"
                connectionStringName="MyAspNetDB"
                enablePasswordRetrieval="false"
                enablePasswordReset="true"
                requiresQuestionAndAnswer="true"
                applicationName="/SamplesRolesApp"
                requiresUniqueEmail="false"
                passwordFormat="Hashed"
                maxInvalidPasswordAttempts="5"
                minRequiredPasswordLength="7"
                minRequiredNonalphanumericCharacters="1"
                passwordAttemptWindow="10"
                passwordStrengthRegularExpression=""                     
                type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </providers>
    </membership>

  ...
  </system.web>

更多信息请查看post。

【讨论】:

嗨,马克,感谢您的回复,但它并没有真正帮助我。 SimpleMembership 不使用这些 web.config 位。

以上是关于Roles.GetRolesForUser();在 MVC 4 中似乎不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Roles.GetRolesForUser 抛出异常对象引用未设置为对象的实例

Roles.GetRolesForUser 在自定义授权属性中不可用

Roles.AddUsersToRoles() 要求 IDENTITY_INSERT 为 ON

如何在 _LoginPartial 的代码部分中获取用户角色?

分配的变量引用在哪里,在堆栈中还是在堆中?

NOIP 2015 & SDOI 2016 Round1 & CTSC 2016 & SDOI2016 Round2游记