首页 > 解决方案 > 无法从 .Net MVC WebApp 访问数据库

问题描述

我一直在尝试在家里的一台机器上本地托管一个 Web 应用程序。我已经能够启动服务器、访问页面等,但是每当我尝试加载需要访问 Db 的页面时,我都会收到以下错误。我只想能够通过一个简单的 .net MVC web app/web api 来操作本地 SQL DB。调试应用程序时一切正常,猜测与运行以托管本地 Db 的 IIS express 有关。我计划保持此服务器只能通过本地网络访问,但我不介意采取安全路线,以防我改变主意。

试过:

我尝试了更多,但由于故障排除选项的数量,它们没有记录。旁注:db 文件位于另一个目录中,具有不同的文件夹权限,如果这很重要的话。

我得到的第一个错误:

Server Error in '/' Application.

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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

将 applicationhost.config 中的 setProfileEnvironment 更改为 true,这修复了第一个错误,但之后给了我一个不同的错误

    <applicationPoolDefaults managedRuntimeVersion="v4.0"> 
        <!--To ensure you can access a webdb, setProfileEnviro to true, Its off for the time being.-->
        <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="false" />
    </applicationPoolDefaults>

新错误:

Directory lookup for the file "C:\Users\x\Desktop\HomeWebApp_n\HomeWebApp\ArduinoWebApp\App_Data\aspnet-ArduinoWebApp-20190313090314.mdf" failed with the operating system error 5(Access is denied.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Directory lookup for the file "C:\Users\x\Desktop\HomeWebApp_n\HomeWebApp\ArduinoWebApp\App_Data\aspnet-ArduinoWebApp-20190313090314.mdf" failed with the operating system error 5(Access is denied.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

WebApp Web.Config 连接设置:

    <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=C:\Users\x\Desktop\HomeWebApp_n\HomeWebApp\ArduinoWebApp\App_Data\aspnet-ArduinoWebApp-20190313090314.mdf;Initial Catalog=aspnet-ArduinoWebApp-20190313090314;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>

我发现并尝试过的其他解决方案不起作用: https ://blogs.msdn.microsoft.com/sqlexpress/2011/12/08/using-localdb-with-full-iis-part-1-user-profile /
https://www.codeproject.com/Articles/674930/Configuring-IIS-ASP-NET-and-SQL-Server
https://docs.microsoft.com/en-us/sql/database-engine/configure- windows/configure-windows-service-accounts-and-permissions?view=sql-server-2017
使用 Asp.net MVC
https://forums.iis.net/t/1213147.aspx?How+I连接到 SQL Server 数据库+can+run+IIS+app+pool+by+domain+account+

标签: sql-serverasp.net-mvciis

解决方案


推荐阅读