简体   繁体   中英

User.IsInRole is not working on server

I am using ASP.NET 2012, SQL Server 2008 and C# for my website. 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. After deploying my website and attempting to login with a user that is in the Admin Role the following error on the server:

A network-related or instance-specific error occurred while establishing a connection to 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. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

My ASP.NET membership database is located on host. Should I use connection string in 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 .

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.

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

Alternative Answer

As your membership application name is called 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.

In the aspnet_Roles table you will find a list of current ASP.NET membership roles. Can you make sure that your role exists there and that the ApplicationId value matches the one from your aspnet_Applications table.

You can run this query to see what roles you have set up and against what ASP.NET Membership application:

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. Specifically, check that:

  • your SQL server is running
  • your SQL server is set to accept connections from the program
  • your program has the correct connection string in the Web.config file

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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