2016-11-18 115 views
0

LTL; FTP在這裏。'System.Web.HttpException'其他信息:無法連接到SQL Server數據庫

我正在做一個電子商務網站,遵循Shakeel Osmani的教程here

當我嘗試在網站上註冊新用戶時,會出現「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

你是什麼意思添加數據庫連接字符串時,「web應用程序無法啓動,在所有」嗎?顯然你的應用程序需要連接字符串來與數據庫實例進行交互,錯誤清楚地表明你的應用程序沒有連接到數據庫。 –

+0

這正是問題所在。當我去我的web.config並添加連接字符串時,webapp拋出'在EntityFramework.dll中發生類型'System.Data.DataException'的異常,但未在用戶代碼中處理 附加信息:發生異常初始化數據庫。看到InnerException的細節.' 由於它不顯示它在哪裏,它變成一個非常惱人的錯誤。 –

回答

0

我工作的同一樣品的項目,我有你有同樣的問題。

我通過增加配置和連接字符串固定它

<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;" />