简体   繁体   English

Web API SQL连接仅在调试时有效

[英]Web API SQL Connection only works when debugging

I'm trying to make an ASP.NET Web API connect to SQL Server and it's not working. 我正在尝试使ASP.NET Web API连接到SQL Server,但它不起作用。 I'm building it from Visual Studio's Web API template, and when I run the code in debug mode it opens a browser to localhost:54723 and it works just as I want it to. 我是从Visual Studio的Web API模板构建它的,当我在调试模式下运行代码时,它会打开浏览器到localhost:54723,并且可以按我的意愿运行。

The problem arises when I publish this same exact code to a real website. 当我将相同的确切代码发布到实际网站时,就会出现问题。 It no longer opens a connection to the SQL Database, instead giving me this lengthy error (the important part seems to be tagged ExceptionMessage): 它不再打开与SQL数据库的连接,而是给了我这个冗长的错误(重要的部分似乎被标记为ExceptionMessage):

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
</ExceptionMessage>
<ExceptionType>System.Data.SqlClient.SqlException</ExceptionType>
<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, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) 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 WebApplication2.Services.HelpdeskHealthHistoryRepository.getAllHelpdeskHealthHistoryInfo() at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>The network path was not found</ExceptionMessage>
<ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
<StackTrace/>
</InnerException>
</Error>

I've searched this website and others and found many potential solutions to the problem, but none seem to work. 我搜索了该网站和其他网站,发现了许多可能解决该问题的方法,但是似乎都没有用。 I've connected to this database before from a Java program in Eclipse so I know I'm allowed to connect to it externally. 我之前已经从Eclipse中的Java程序连接到该数据库,所以我知道可以从外部连接到该数据库。

I suspect that the issue has something to do with the database not allowing access to foreign computers, as outlined somewhat in this post: Visual studio debug access to external database but how can I solve this problem if I want any computer to be able to access this? 我怀疑此问题与数据库不允许访问外部计算机有关,如本文中所概述: Visual Studio调试对外部数据库的访问,但是如果我希望任何计算机都可以访问该如何解决此问题这个?

You need to configure SQL Server to accept remote connections. 您需要配置SQL Server接受远程连接。

SSMS 短信服务

  1. Open SQL Management Studio and right-click server name in the left pane and select Properties. 打开SQL Management Studio,然后在左窗格中右键单击服务器名称,然后选择“属性”。
  2. Select Connections in the left pane and make sure that checkbox Allow remote connections to this server is selected 在左窗格中选择“连接”,并确保选中了“允许到该服务器的远程连接”复选框


SQL Server Configuration Manager SQL Server配置管理器

  1. Open SQL Server Configuration Manager and click on “SQL Server Services” in the left pane. 打开SQL Server配置管理器,然后在左窗格中单击“ SQL Server服务”。
  2. In the center pane, is a column that lists the Process ID for each running service. 在中间窗格中,是一列,列出了每个正在运行的服务的进程ID。 Look for the PID in the row for SQL Server. 在SQL Server的行中查找PID。 Identify the port that that PID is listening on by typing this into a command prompt: netstat -ano | find /i “PID-Number-Of-SQL-Server” 通过在命令提示符下键入以下命令来标识PID正在侦听的端口: netstat -ano | find /i “PID-Number-Of-SQL-Server” netstat -ano | find /i “PID-Number-Of-SQL-Server”
  3. If there is no results from the command executed in step 3 its because TCP/IP protocol is disabled and must be enabled. 如果步骤3中执行的命令没有结果,则是因为TCP / IP协议已禁用并且必须启用。 In SQL Server Configuration Manager click on SQL Server Network Configuration in the left pane and right-click TCP/IP protocol and select option Enable. 在SQL Server配置管理器中,单击左窗格中的“ SQL Server网络配置”,然后右键单击“ TCP / IP协议”,然后选择“启用”选项。
  4. Restart SQL Server service and identify the process ID assigned to SQL service. 重新启动SQL Server服务,并标识分配给SQL服务的进程ID。
  5. In the command prompt execute command: netstat -ano | find /i “6524” 在命令提示符下,执行命令: netstat -ano | find /i “6524” netstat -ano | find /i “6524”
  6. In SQL Server Configuration Manager and click on SQL Server Network Configuration in the left pane and right-click TCP/IP protocol and select option Properties. 在SQL Server配置管理器中,单击左窗格中的“ SQL Server网络配置”,然后右键单击“ TCP / IP协议”,然后选择选项“属性”。 Goto IP Address tab and scroll-down to APAll section. 转到IP地址选项卡,然后向下滚动到APAll部分。 Remove value for TCP Dynamic Ports and enter the port 1433 for TCP Port. 删除“ TCP动态端口”的值,然后为“ TCP端口”输入端口1433。
  7. Restart SQL Server service, identify new process ID assigned to SQL service and in the command prompt execute command: netstat -ano | find /i “3948” 重新启动SQL Server服务,标识分配给SQL服务的新进程ID,然后在命令提示符下执行命令: netstat -ano | find /i “3948” netstat -ano | find /i “3948” . netstat -ano | find /i “3948”
  8. Open SQL Server Configuration Manager and click on “SQL Server Services” in the left pane, right-click SQL Server Browser service and select Properties. 打开SQL Server配置管理器,然后单击左窗格中的“ SQL Server服务”,右键单击SQL Server Browser服务,然后选择“属性”。
  9. Go to Service tab and for Start Mode option change start type to Automatic. 转到服务选项卡,对于开始模式选项,将开始类型更改为自动。 Click Start button to start SQL Browser service. 单击开始按钮以启动SQL Browser服务。 Confirm that SQL Server Browser service is up and running. 确认SQL Server浏览器服务已启动并正在运行。


Windows Firewall Windows防火墙

  1. A port exception for TCP Port 1433. In the New Inbound Rule Wizard dialog, use the following information to create a port exception: TCP端口1433的端口例外。在“新建入站规则向导”对话框中,使用以下信息创建端口例外:
    • Select Port 选择端口
    • Select TCP and specify port 1433 选择TCP并指定端口1433
    • Allow the connection 允许连接
    • Choose all three profiles (Domain, Private & Public) 选择所有三个配置文件(域,私有和公共)
    • Name the rule “SQL – TCP 1433” 将规则命名为“ SQL – TCP 1433”
  2. A port exception for UDP Port 1434. Click New Rule again and use the following information to create another port exception: UDP端口1434的端口例外。再次单击“新建规则”,然后使用以下信息创建另一个端口例外:
    • Select Port 选择端口
    • Select UDP and specify port 1434 选择UDP并指定端口1434
    • Allow the connection 允许连接
    • Choose all three profiles (Domain, Private & Public) 选择所有三个配置文件(域,私有和公共)
    • Name the rule “SQL – UDP 1434 将规则命名为“ SQL – UDP 1434
  3. A program exception for sqlservr.exe. sqlservr.exe的程序异常。 Click New Rule again and use the following information to create a program exception: 再次单击“新建规则”,然后使用以下信息创建程序异常:
    • Select Program 选择程序
    • Click Browse to select 'sqlservr.exe' at this location: [C:\\Program Files\\Microsoft SQL Server\\MSSQL11.\\MSSQL\\Binn\\sqlservr.exe] where is the name of your SQL instance. 单击“浏览”在以下位置选择“ sqlservr.exe”:[C:\\ Program Files \\ Microsoft SQL Server \\ MSSQL11。\\ MSSQL \\ Binn \\ sqlservr.exe]其中是您的SQL实例的名称。
    • Allow the connection 允许连接
    • Choose all three profiles (Domain, Private & Public) 选择所有三个配置文件(域,私有和公共)
    • Name the rule SQL – sqlservr.exe 将规则命名为SQL – sqlservr.exe
  4. A program exception for sqlbrowser.exe Click New Rule again and use the following information to create another program exception: sqlbrowser.exe的程序异常再次单击“新建规则”,然后使用以下信息创建另一个程序异常:
    • Select Program 选择程序
    • Click Browse to select sqlbrowser.exe at this location: [C:\\Program Files (x86)\\Microsoft SQL Server\\90\\Shared\\sqlbrowser.exe]. 单击浏览以在以下位置选择sqlbrowser.exe:[C:\\ Program Files(x86)\\ Microsoft SQL Server \\ 90 \\ Shared \\ sqlbrowser.exe]。
    • Allow the connection 允许连接
    • Choose all three profiles (Domain, Private & Public) 选择所有三个配置文件(域,私有和公共)
    • Name the rule SQL – sqlbrowser.exe 将规则命名为SQL – sqlbrowser.exe

Source 资源
http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/ http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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