如何通过IIS发布的ASP.NET Core API访问同域文件服务器共享?
解决ASP.NET Core API访问局域网共享目录的问题
1. 修复路径解析错误
你遇到的DirectoryNotFoundException核心原因是路径字符串的转义问题。在C#中,单个反斜杠\是转义字符,直接写\192.168.100.7\ofertashistorico会被解析为项目本地目录下的相对路径,而非局域网共享路径。
解决方法:
- 使用逐字字符串(加
@前缀):string sharePath = @"\\192.168.100.7\ofertashistorico"; var files = Directory.GetFiles(sharePath); - 或者用双反斜杠转义:
string sharePath = "\\\\192.168.100.7\\ofertashistorico"; var files = Directory.GetFiles(sharePath);
2. 处理共享目录的凭据验证
默认情况下,ASP.NET Core API运行时的身份(本地开发是当前登录用户/开发服务器身份,IIS部署是应用池身份)可能没有访问目标共享目录的权限,需要通过以下方式处理:
本地开发环境
如果共享目录需要特定账号密码才能访问,可以通过Windows API挂载共享并传入凭据,示例代码如下:
首先定义必要的结构体和API调用:
using System; using System.Runtime.InteropServices; public class NetworkShareHelper { [StructLayout(LayoutKind.Sequential)] private struct NETRESOURCE { public int dwScope; public int dwType; public int dwDisplayType; public int dwUsage; public string lpLocalName; public string lpRemoteName; public string lpComment; public string lpProvider; } [DllImport("mpr.dll")] private static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags); [DllImport("mpr.dll")] private static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce); public static int ConnectToShare(string remotePath, string username, string password) { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = 1; // RESOURCETYPE_DISK nr.lpRemoteName = remotePath; return WNetAddConnection2(ref nr, password, username, 0); } public static int DisconnectFromShare(string remotePath) { return WNetCancelConnection2(remotePath, 0, true); } }
然后在API中调用:
var sharePath = @"\\192.168.100.7\ofertashistorico"; // 先建立连接 var connectResult = NetworkShareHelper.ConnectToShare(sharePath, "共享账号", "共享密码"); if (connectResult == 0) // 连接成功 { try { var files = Directory.GetFiles(sharePath); // 处理文件逻辑 } finally { // 断开连接 NetworkShareHelper.DisconnectFromShare(sharePath); } } else { // 处理连接失败,比如返回错误信息 }
IIS部署环境
部署到IIS时,推荐通过应用池身份授予权限:
- 打开IIS管理器,找到你的应用池,右键选择“高级设置”
- 将“标识”改为具有共享目录访问权限的域账号或本地账号(需提前在文件服务器上给该账号分配共享权限和NTFS权限)
- 若必须在代码中传入凭据,务必不要硬编码密码,使用.NET的机密管理器(
dotnet user-secrets)或加密存储方案。
3. 额外检查项
- 确保API服务器和文件服务器在同一局域网,网络连通性正常(可以用ping测试)
- 验证文件服务器的共享权限:右键共享文件夹→“属性”→“共享”→检查是否允许目标账号访问
- 验证NTFS权限:右键共享文件夹→“属性”→“安全”→确保目标账号有读取权限
内容的提问来源于stack exchange,提问作者kintela
相关产品推荐
相关产品推荐

