sql-server – MVC4:UserIsInRole – 无法连接到SQL Server数据库

前端之家收集整理的这篇文章主要介绍了sql-server – MVC4:UserIsInRole – 无法连接到SQL Server数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
打破了我的头脑,昨天它工作正常,今天似乎被打破了:

该行生成错误

@if (Roles.IsUserInRole(HttpContext.Current.User.Identity.Name,"Admin"))

错误是:
无法连接到sql Server数据库.

全部例外:

System.Web.HttpException was unhandled by user code
  HResult=-2147467259
  Message=Unable to connect to sql Server database.
  Source=System.Web
  ErrorCode=-2147467259
  WebEventCode=0
  StackTrace:
       at System.Web.DataAccess.sqlConnectionHelper.CreateMdfFile(String fullFileName,String dataDir,String connectionString)
       at System.Web.DataAccess.sqlConnectionHelper.EnsureDBFile(String connectionString)
       at System.Web.DataAccess.sqlConnectionHelper.GetConnection(String connectionString,Boolean revertImpersonation)
       at System.Web.Security.sqlRoleProvider.GetRolesForUser(String username)
       at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)
       at System.Web.Security.RolePrincipal.IsInRole(String role)
       at System.Web.Security.Roles.IsUserInRole(String username,String roleName)
       at ASP._Page_Views_Shared__LoginPartial_cshtml.Execute() in e:\LeasingWeb\LeasingWeb\Views\Shared\_LoginPartial.cshtml:line 10
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,TextWriter writer,WebPageRenderingBase startPage)
       at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,Object instance)
       at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext,TextWriter writer)
       at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName,ViewDataDictionary viewData,Object model,ViewEngineCollection viewEngineCollection)
       at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper,String partialViewName,ViewDataDictionary viewData)
       at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper,String partialViewName)
       at ASP._Page_Views_Shared__Layout_cshtml.Execute() in e:\LeasingWeb\LeasingWeb\Views\Shared\_Layout.cshtml:line 35
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,WebPageRenderingBase startPage)
       at System.Web.WebPages.WebPageBase.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer)
       at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
       at System.Web.WebPages.WebPageBase.Write(HelperResult result)
       at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName,Action`1 body)
       at System.Web.WebPages.WebPageBase.PopContext()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,TextWriter writer)
       at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext,ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter,ResultExecutingContext preContext,Func`1 continuation)
  InnerException: System.Web.HttpException
       HResult=-2147467259
       Message=Unable to connect to sql Server database.
       Source=System.Web
       ErrorCode=-2147467259
       WebEventCode=0
       StackTrace:
            at System.Web.Management.sqlServices.GetsqlConnection(String server,String user,String password,Boolean trusted,String connectionString)
            at System.Web.Management.sqlServices.SetupApplicationServices(String server,String connectionString,String database,String dbFileName,sqlFeatures features,Boolean install)
            at System.Web.Management.sqlServices.Install(String database,String connectionString)
            at System.Web.DataAccess.sqlConnectionHelper.CreateMdfFile(String fullFileName,String connectionString)
       InnerException: System.Data.sqlClient.sqlException
            HResult=-2146232060
            Message=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)
            Source=.Net sqlClient Data Provider
            ErrorCode=-2146232060
            Class=20
            LineNumber=0
            Number=-1
            Server=""
            State=0
            StackTrace:
                 at System.Data.sqlClient.sqlInternalConnection.OnError(sqlException exception,Boolean breakConnection,Action`1 wrapCloseInAction)
                 at System.Data.sqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)
                 at System.Data.sqlClient.TdsParser.Connect(ServerInfo serverInfo,sqlInternalConnectionTds connHandler,Boolean ignoreSniOpenTimeout,Int64 timerExpire,Boolean encrypt,Boolean trustServerCert,Boolean integratedSecurity,Boolean withFailover)
                 at System.Data.sqlClient.sqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo,String newPassword,SecureString newSecurePassword,TimeoutTimer timeout,Boolean withFailover)
                 at System.Data.sqlClient.sqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo,Boolean redirectedUserInstance,sqlConnectionString connectionOptions,sqlCredential credential,TimeoutTimer timeout)
                 at System.Data.sqlClient.sqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout,Boolean redirectedUserInstance)
                 at System.Data.sqlClient.sqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,Object providerInfo,sqlConnectionString userConnectionOptions)
                 at System.Data.sqlClient.sqlConnectionFactory.CreateConnection(DbConnectionOptions options,DbConnectionPoolKey poolKey,Object poolGroupProviderInfo,DbConnectionPool pool,DbConnection owningConnection,DbConnectionOptions userOptions)
                 at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection,DbConnectionPoolGroup poolGroup,DbConnectionOptions userOptions)
                 at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection,TaskCompletionSource`1 retry,DbConnectionOptions userOptions,DbConnectionInternal& connection)
                 at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection,DbConnectionFactory connectionFactory,DbConnectionOptions userOptions)
                 at System.Data.sqlClient.sqlConnection.TryOpen(TaskCompletionSource`1 retry)
                 at System.Data.sqlClient.sqlConnection.Open()
                 at System.Web.Management.sqlServices.GetsqlConnection(String server,String connectionString)
            InnerException:

正如我所说,这已经工作了几天,我一直在使用在创建一个新的MVC4项目时创建的默认用户数据库.

Web.config文件

<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" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-LeasingWeb-20130113013313;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-LeasingWeb-20130113013313.mdf" providerName="System.Data.sqlClient" />
  </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" />
  </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,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,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="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

客户端错误

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)

DB表似乎很好,用户和角色存在,就像以前一样.

解决方法

添加
[InitializeSimpleMembership]

回到HomeController的顶部修复了这个问题.

属性说明:

http://blogs.msdn.com/b/rickandy/archive/2012/08/15/initializesimplemembership-attribute-and-simplemembership-exceptions.aspx

原文链接:https://www.f2er.com/mssql/81965.html

猜你在找的MsSQL相关文章