2016-11-18 7 views
0

LTL; FTP hier.'System.Web.HttpException' Zusätzliche Informationen: Verbindung zur SQL Server-Datenbank nicht möglich

Ich mache eine eCommerce-Site nach Shakeel Osmanis Tutorial here.

Das Problem tritt auf, wenn ich versuche, einen neuen Benutzer auf der Website zu registrieren, wirft es eine "'System.Web.HttpException' Zusätzliche Informationen: Verbindung mit SQL Server-Datenbank kann nicht hergestellt werden." Ausnahme, und ich kann das Problem nirgends finden.

Ich verwende VS2015 codefirst Ansatz, und der Code für die AccountsController ist folgende:

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 
 
    } 
 
}

Mein Web.config ist:

<?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>

Ich habe dies sehr bald (Class-Projekt) zu liefern, und ich habe so ziemlich jede Antwort folgte ich darüber in diesen und anderen Foren finden konnte, wie ein

Tag

<remove name="RoleManager" />
Zugabe in web.config, Komische ist, dass, wenn ich hinzufügen, die Verbindungszeichenfolge:

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

Die Webanwendung startet überhaupt nicht.

Bitte helfen!

Die vollständige Ausnahme ist:

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

Was meinst du mit „die Webapp überhaupt nicht gestartet werden“ beim DB-Verbindungszeichenfolge hinzufügen? Offensichtlich benötigt Ihre App eine Verbindungszeichenfolge, um mit DB-Instanzen zu interagieren. Der Fehler besagt eindeutig, dass Ihre App keine Verbindung zur DB hat. –

+0

Das ist genau das Problem. Als ich zu meinem web.config gehen und die Verbindungszeichenfolge hinzufügen, die Webapp 'eine Ausnahme vom Typ‚System.Data.DataException‘wirft aufgetreten in EntityFramework.dll wurde aber in Benutzercode Zusätzliche Informationen nicht behandelt: Eine Ausnahme ist aufgetreten, während Initialisierung der Datenbank Sehen Sie sich die Innerexception für details.' , die in einen sehr ärgerlichen Fehler dreht, da es zeigt nicht, wo es ist. –

Antwort

0

Ich bin auf der gleichen Beispielprojekt arbeiten, und ich hatte dasselbe Problem, das Sie haben.

ich es fest von config und Verbindungszeichenfolge Hinzufügen

<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> 

und

<add name="SqlConn" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=aspnetdb;Integrated Security=True;" /> 
Verwandte Themen