2016-11-18 23 views
0

LTL;ここにFTPしてください。'System.Web.HttpException'追加情報:SQL Serverデータベースに接続できません

私はShakeel Osmaniのチュートリアルhereに従った電子商取引サイトを行っています。

新しいユーザーをWebサイトに登録しようとすると、 "System.Web.HttpException 'がスローされます。追加情報:SQL Serverデータベースに接続できません。例外があり、私は問題をどこにも見つけることができません。

私はVS2015 codefirstアプローチを使用していて、AccountsControllerのためのコードは以下の通りです:

using System; 
 
using System.Web.Mvc; 
 
using System.Web.Security; 
 
using eProject.Models; 
 

 
namespace eProject.Controllers 
 
{ 
 
    public class AccountsController : Controller 
 
    { 
 

 
     private void MigrateShoppingCart(string userName) 
 
     { 
 
      var cart = ShoppingCart.GetCart(this.HttpContext); 
 

 
      cart.MigrateCart(userName); 
 
      Session[ShoppingCart.CartSessionKey] = userName; 
 
     } 
 

 
     public ActionResult LogOn() 
 
     { 
 
      return View(); 
 
     } 
 

 
     [HttpPost] 
 
     public ActionResult LogOn(LogOnModel model, string returnUrl) 
 
     { 
 
      if (ModelState.IsValid) 
 
      { 
 
       if (Membership.ValidateUser(model.UserName, model.Password)) 
 
       { 
 
        MigrateShoppingCart(model.UserName); 
 

 
        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
 
        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
 
         && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
 
        { 
 
         return Redirect(returnUrl); 
 
        } 
 
        else 
 
        { 
 
         return RedirectToAction("Index", "Home"); 
 
        } 
 
       } 
 
       else 
 
       { 
 
        ModelState.AddModelError("", "The user name or password provided is incorrect."); 
 
       } 
 
      } 
 

 
      // If we got this far, something failed, redisplay form 
 
      return View(model); 
 
     } 
 

 
     public ActionResult LogOff() 
 
     { 
 
      FormsAuthentication.SignOut(); 
 
      var cart = ShoppingCart.GetCart(this.HttpContext); 
 
      cart.EmptyCart(); 
 

 
      return RedirectToAction("Index", "Home"); 
 
     } 
 

 
     public ActionResult Register() 
 
     { 
 
      return View(); 
 
     } 
 

 
     [HttpPost] 
 
     public ActionResult Register(RegisterModel model) 
 
     { 
 
      if (ModelState.IsValid) 
 
      { 
 
       // Attempt to register the user 
 
       MembershipCreateStatus createStatus; 
 
       Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus); 
 

 
       if (createStatus == MembershipCreateStatus.Success) 
 
       { 
 
        MigrateShoppingCart(model.UserName); 
 

 
        FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); 
 
        return RedirectToAction("Index", "Home"); 
 
       } 
 
       else 
 
       { 
 
        ModelState.AddModelError("", ErrorCodeToString(createStatus)); 
 
       } 
 
      } 
 

 
      // If we got this far, something failed, redisplay form 
 
      return View(model); 
 
     } 
 

 
     [Authorize] 
 
     public ActionResult ChangePassword() 
 
     { 
 
      return View(); 
 
     } 
 

 
     [Authorize] 
 
     [HttpPost] 
 
     public ActionResult ChangePassword(ChangePasswordModel model) 
 
     { 
 
      if (ModelState.IsValid) 
 
      { 
 

 
       // ChangePassword will throw an exception rather 
 
       // than return false in certain failure scenarios. 
 
       bool changePasswordSucceeded; 
 
       try 
 
       { 
 
        MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); 
 
        changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); 
 
       } 
 
       catch (Exception) 
 
       { 
 
        changePasswordSucceeded = false; 
 
       } 
 

 
       if (changePasswordSucceeded) 
 
       { 
 
        return RedirectToAction("ChangePasswordSuccess"); 
 
       } 
 
       else 
 
       { 
 
        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); 
 
       } 
 
      } 
 

 
      // If we got this far, something failed, redisplay form 
 
      return View(model); 
 
     } 
 

 
     public ActionResult ChangePasswordSuccess() 
 
     { 
 
      return View(); 
 
     } 
 

 
     #region Status Codes 
 
     private static string ErrorCodeToString(MembershipCreateStatus createStatus) 
 
     { 
 
      // See http://go.microsoft.com/fwlink/?LinkID=177550 for 
 
      // a full list of status codes. 
 
      switch (createStatus) 
 
      { 
 
       case MembershipCreateStatus.DuplicateUserName: 
 
        return "User name already exists. Please enter a different user name."; 
 

 
       case MembershipCreateStatus.DuplicateEmail: 
 
        return "A user name for that e-mail address already exists. Please enter a different e-mail address."; 
 

 
       case MembershipCreateStatus.InvalidPassword: 
 
        return "The password provided is invalid. Please enter a valid password value."; 
 

 
       case MembershipCreateStatus.InvalidEmail: 
 
        return "The e-mail address provided is invalid. Please check the value and try again."; 
 

 
       case MembershipCreateStatus.InvalidAnswer: 
 
        return "The password retrieval answer provided is invalid. Please check the value and try again."; 
 

 
       case MembershipCreateStatus.InvalidQuestion: 
 
        return "The password retrieval question provided is invalid. Please check the value and try again."; 
 

 
       case MembershipCreateStatus.InvalidUserName: 
 
        return "The user name provided is invalid. Please check the value and try again."; 
 

 
       case MembershipCreateStatus.ProviderError: 
 
        return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; 
 

 
       case MembershipCreateStatus.UserRejected: 
 
        return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; 
 

 
       default: 
 
        return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; 
 
      } 
 
     } 
 
     #endregion 
 
    } 
 
}

私の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=301880 
 
    --> 
 
<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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
 
    </configSections> 
 
    <appSettings> 
 
    <add key="webpages:Version" value="3.0.0.0" /> 
 
    <add key="webpages:Enabled" value="false" /> 
 
    <add key="ClientValidationEnabled" value="true" /> 
 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
 
    <add key="enableSimpleMembership" value="true" /> 
 
    </appSettings> 
 
    <system.web> 
 
    <compilation debug="true" targetFramework="4.5.2" /> 
 
    <httpRuntime targetFramework="4.5.2" /> 
 
    </system.web> 
 
    <runtime> 
 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
 
     <dependentAssembly> 
 
     <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> 
 
     <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> 
 
     </dependentAssembly> 
 
     <dependentAssembly> 
 
     <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> 
 
     <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> 
 
     </dependentAssembly> 
 
     <dependentAssembly> 
 
     <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> 
 
     <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> 
 
     </dependentAssembly> 
 
     <dependentAssembly> 
 
     <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> 
 
     <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> 
 
     </dependentAssembly> 
 
     <dependentAssembly> 
 
     <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> 
 
     <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> 
 
     </dependentAssembly> 
 
     <dependentAssembly> 
 
     <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> 
 
     <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> 
 
     </dependentAssembly> 
 
    </assemblyBinding> 
 
    </runtime> 
 
    <system.codedom> 
 
    <compilers> 
 
     <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> 
 
     <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /> 
 
    </compilers> 
 
    </system.codedom> 
 
    <system.webServer> 
 
    <modules> 
 
     <remove name="RoleManager" /> 
 
    </modules> 
 
    </system.webServer> 
 
    <entityFramework> 
 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> 
 
     <parameters> 
 
     <parameter value="mssqllocaldb" /> 
 
     </parameters> 
 
    </defaultConnectionFactory> 
 
    <providers> 
 
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
 
    </providers> 
 
    </entityFramework> 
 
</configuration>

私はこの非常にすぐに(クラスプロジェクト)を提供しなければならないと私は中

<remove name="RoleManager" />

タグを追加するように、私はこれと他のフォーラムでこのことについて見つけることができるほとんどすべての答えを踏襲していますweb.configファイル、面白いことは、私は、接続文字列を追加したときということです:

<connectionStrings> 
 
    <add name="MvcAffableBean" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MvcAffableBean;Integrated Security=True" providerName="System.Data.SqlClient" /> 
 
    </connectionStrings>

webappがまったく起動しません。

助けてください!

完全な例外は次のとおりです。

System.Web.HttpException was unhandled by user code 
 
    ErrorCode=-2147467259 
 
    HResult=-2147467259 
 
    Message=Unable to connect to SQL Server database. 
 
    Source=System.Web 
 
    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.SqlMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) 
 
     at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) 
 
     at eProject.Controllers.AccountsController.Register(RegisterModel model) in c:\users\hermes lizama\documents\visual studio 2015\Projects\eProject\eProject\Controllers\AccountsController.cs:line 75 
 
     at lambda_method(Closure , ControllerBase , Object[]) 
 
     at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) 
 
     at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) 
 
     at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) 
 
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) 
 
     at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) 
 
     at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() 
 
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) 
 
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() 
 
     at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() 
 
    InnerException: 
 
     ErrorCode=-2147467259 
 
     HResult=-2147467259 
 
     Message=Unable to connect to SQL Server database. 
 
     Source=System.Web 
 
     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 user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) 
 
      at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) 
 
      at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) 
 
     InnerException: 
 
      Class=20 
 
      ErrorCode=-2146232060 
 
      HResult=-2146232060 
 
      LineNumber=0 
 
      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) 
 
      Number=-1 
 
      Server="" 
 
      Source=.Net SqlClient Data Provider 
 
      State=0 
 
      StackTrace: 
 
       at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) 
 
       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 oldConnection, DbConnectionInternal& connection) 
 
       at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) 
 
       at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) 
 
       at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) 
 
       at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) 
 
       at System.Data.SqlClient.SqlConnection.Open() 
 
       at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) 
 
      InnerException:

+1

を追加することによって、それを修正?明らかに、あなたのアプリケーションにはDBインスタンスと対話するための接続文字列が必要ですが、エラーは明らかにアプリケーションがDBに接続していないと言います。 –

+0

これはまさに問題です。 Web.configにアクセスして接続文字列を追加すると、Webappが「System.Data.DataException」という例外がEntityFramework.dllで発生しましたが、ユーザーコードで処理されませんでした 追加情報:例外が発生しましたデータベースを初期化する。詳細については、InnerExceptionを参照してください。 それはどこに表示されていないので、非常に迷惑なエラーになります。 –

答えて

0

私は同じサンプルプロジェクトに取り組んでいると私はあなたが持っている同じ問題がありました。

私はあなたのDB接続文字列を追加するとき、「Webアプリケーションがまったく起動しない」とは何を意味するか設定し、接続文字列

<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15"> 
    <providers> 
    <clear /> 
    <add 
     name="SqlMembershipProvider" 
     type="System.Web.Security.SqlMembershipProvider" 
     connectionStringName="SqlConn" 
     applicationName="MembershipAndRoleProviderSample" 
     enablePasswordRetrieval="false" 
     enablePasswordReset="false" 
     requiresQuestionAndAnswer="false" 
     requiresUniqueEmail="true" 
     passwordFormat="Hashed" /> 
    </providers> 
</membership> 

<add name="SqlConn" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=aspnetdb;Integrated Security=True;" /> 
関連する問題