简体   繁体   English

User.IsInRole在服务器上不起作用

[英]User.IsInRole is not working on server

I am using ASP.NET 2012, SQL Server 2008 and C# for my website. 我的网站使用的是ASP.NET 2012,SQL Server 2008和C#。 When I execute the following code: 当我执行以下代码时:

if(User.IsInRole("Admin"))
    Response.Redirect("test.aspx");

In the Default.aspx.cs and ran in Visual Studio locally there is no error. Default.aspx.cs ,在Visual Studio中本地运行时没有错误。 After deploying my website and attempting to login with a user that is in the Admin Role the following error on the server: 部署我的网站并尝试以具有Admin Role的用户登录后,服务器上出现以下错误:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. 建立与SQL Server的连接时发生与网络相关或特定于实例的错误。 The server was not found or was not accessible. 服务器未找到或无法访问。 Verify that the instance name is correct and that SQL Server is configured to allow remote connections. 验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (提供者:SQL网络接口,错误:26-指定服务器/实例时出错)

My ASP.NET membership database is located on host. 我的ASP.NET成员资格数据库位于主机上。 Should I use connection string in Default.aspx.cs ? 我应该在Default.aspx.cs使用连接字符串吗? If yes, how can I write for this purpose? 如果是,我该如何写?

I am sure that the User that I log in with with is in the Admin Role . 我确定与我一起登录的User位于“ Admin Role

web.config : web.config

<configuration>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
  </appSettings>
  <connectionStrings>
    <add name="MembersConnectionString" 
         connectionString="workstation id=mssql;packet size=4096;user id=shahi_SQLLogin_1;pwd=password;data source=mssql;persist security info=False;initial catalog=akhbarrr" />
    <add name="SabteAKhabar" 
         connectionString="workstation id=mssql;packet size=4096;user id=shahi_SQLLogin_1;pwd=password;data source=mssql;persist security info=False;initial catalog=akhbarrr" />
    <add name="ConnectionString" 
         connectionString="workstation id=mssql;packet size=4096;user id=shahi_SQLLogin_1;pwd=password;data source=mssql;persist security info=False;initial catalog=akhbarrr" />
    <add name="akhbarrConnectionString" 
         connectionString="workstation id=mssql;packet size=4096;user id=shahi_SQLLogin_1;pwd=password;data source=mssql;persist security info=False;initial catalog=akhbarrr"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <customErrors mode="Off">
      <error statusCode="403" redirect="access.aspx"/>
      <error statusCode="404" redirect="nofile.aspx"/>
    </customErrors>
    <anonymousIdentification enabled="true"/>
    <profile enabled="true" defaultProvider="AspNetSqlProfileProvider">
      <properties>
        <add name="FirstName" allowAnonymous="false"/>
        <add name="LastName" allowAnonymous="false"/>
        <add name="AkharinMadrak" allowAnonymous="false"/>
        <add name="Reshte" allowAnonymous="false"/>
        <add name="Gerayesh" allowAnonymous="false"/>
        <add name="NahveAshnayi" allowAnonymous="false"/>
        <add name="Address" allowAnonymous="false"/>
        <add name="PostalKod" allowAnonymous="false"/>
        <add name="City" allowAnonymous="false"/>
        <add name="Town" allowAnonymous="false"/>
        <add name="Number" allowAnonymous="false"/>
        <add name="BirthDay" type="System.DateTime" allowAnonymous="false"/>
      </properties>
    </profile>
    <authorization>
      <allow roles="Managers"/>
      <allow roles="Admin"/>
      <allow roles="AdminAsli"/>
    </authorization>
    <authentication mode="Forms">
      <forms timeout="5" cookieless="AutoDetect" protection="All"/>
    </authentication>
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear/>
        <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="MembersConnectionString" applicationName="MyApplication" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed"/>
      </providers>
    </membership>
    <roleManager enabled="true"/>
    <pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never" enableViewStateMac="false"/>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <httpRuntime/>
    <machineKey validationKey="1234567890123456789012345678901234567890AAAAAAAAAA" decryptionKey="123456789012345678901234567890123456789012345678" validation="SHA1" decryption="Auto"/>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <add name="MSCaptcha" path="CaptchaImage.axd" verb="GET" type="MSCaptcha.CaptchaImageHandler, MSCaptcha" preCondition="integratedMode,runtimeVersionv2.0"/>
    </handlers>
  </system.webServer>
  <system.net>
    <mailSettings>
      <smtp from="xxxxxx@gmail.com">
        <network host="smtp.gmail.com" password="xxxxxx" port="587" userName="farzanehsd@gmail.com" enableSsl="true"/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

There is no error with your C# code as the error message is clearly telling you. 您的C#代码没有错误,因为错误消息清楚地告诉您。

There is an error connecting to your database which is mostly likely caused by missing or incorrect entries in your configuration file. 连接到数据库时出错,这很可能是由于配置文件中的条目丢失或不正确引起的。

Sample configuration: 样本配置:

<connectionStrings>
    <add name="MembersConnectionString" 
        connectionString="Data Source=akhbarrr.mssql.somee.com;packet size=4096;User Id=YourUserID;Password=YourPassword;persist security info=False;Initial Catalog=akhbarrr" />
    <add name="SabteAKhabar" 
        connectionString="Data Source=akhbarrr.mssql.somee.com;packet size=4096;User Id=YourUserID;Password=YourPassword;persist security info=False;Initial Catalog=akhbarrr" />
    <add name="ConnectionString" 
        connectionString="Data Source=akhbarrr.mssql.somee.com;packet size=4096;User Id=YourUserID;Password=YourPassword;persist security info=False;Initial Catalog=akhbarrr" />
    <add name="akhbarrConnectionString" 
        connectionString="Data Source=akhbarrr.mssql.somee.com;packet size=4096;User Id=YourUserID;Password=YourPassword;persist security info=False;Initial Catalog=akhbarrr"
      providerName="System.Data.SqlClient" />
</connectionStrings>

Reference / Further Reading: For more information on the configuration side of ASP.NET membership please see: http://msdn.microsoft.com/en-us/library/6e9y4s5t(v=vs.100).aspx 参考/进一步阅读:有关ASP.NET成员身份配置方面的更多信息,请参见: http : //msdn.microsoft.com/zh-cn/library/6e9y4s5t(v=vs.100).aspx

Alternative Answer 替代答案

As your membership application name is called MyApplication . 由于您的会员资格申请名称称为MyApplication Can you make sure that the ApplicationId value in your aspnet_Applications database table matches the values in your aspnet_Roles tables for your roles. 你能确保ApplicationId在你的价值aspnet_Applications数据库表中的值相匹配aspnet_Roles表为您的角色。

In the aspnet_Roles table you will find a list of current ASP.NET membership roles. aspnet_Roles表中,您将找到当前ASP.NET成员身份角色的列表。 Can you make sure that your role exists there and that the ApplicationId value matches the one from your aspnet_Applications table. 您是否可以确保您的角色在那里,并且ApplicationId值与aspnet_Applications表中的角色匹配。

You can run this query to see what roles you have set up and against what ASP.NET Membership application: 您可以运行此查询来查看已设置的角色以及针对哪个ASP.NET Membership应用程序的角色:

SELECT APP.ApplicationId, APP.ApplicationName, ROLES.RoleName, ROLES.RoleId 
FROM dbo.aspnet_Applications AS APP
JOIN dbo.aspnet_Roles AS ROLES ON APP.ApplicationId = ROLES.ApplicationId

This is nothing to do with the user or the role. 这与用户或角色无关。 The error message is telling you what's wrong and what to do: your program cannot access your SQL database, so you need to check that it's set up properly. 该错误消息告诉您出什么问题和怎么做:您的程序无法访问SQL数据库,因此您需要检查其设置是否正确。 Specifically, check that: 具体来说,请检查以下内容:

  • your SQL server is running 您的SQL服务器正在运行
  • your SQL server is set to accept connections from the program 您的SQL Server设置为接受来自程序的连接
  • your program has the correct connection string in the Web.config file 您的程序在Web.config文件中具有正确的连接字符串

You've defined all the details necessary for the membership provider - but nothing for the role provider ! 您已经为成员资格提供程序定义了所有必要的详细信息,但对于角色提供程序则没有定义任何详细信息!

<!-- you're providing all the details for the membership provider ...... -->
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
   <providers>
      <clear/>
      <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="MembersConnectionString" applicationName="MyApplication" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed"/>
      </providers>
</membership>

<!-- but nothing at all really for the role provider. -->
<roleManager enabled="true"/>

See this blog post by Scott Allen on how to define the role providers details, define where to find the information and what role provider to use - and do the same as you did for membership for the role provider, too! 请参阅Scott Allen的博客文章,内容涉及如何定义角色提供者详细信息,定义在何处查找信息以及使用哪个角色提供者-以及与角色提供者成员身份相同的操作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM