You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core跨服务器访问静态文件的问题与解决方案

静态文件跨应用转发问题及解决方案

问题背景

我有两个.NET Core Web应用:

  • MiddlewareApp:面向互联网,负责接收客户端加密请求,解密后转发至另一服务器的MainApp
  • MainApp:包含控制器及WWWRoot中的静态文件

目前MiddlewareApp转发请求到MainApp控制器可正常获取数据,但无法访问MainApp的静态文件。

本地环境配置:

  • MainApp运行在7000端口
  • MiddlewareApp运行在7001端口

MainApp静态文件配置

MainApp的Program文件中静态文件相关配置如下:

.........
app.UseHttpsRedirection();

//to allow access files in wwwroot without any server-side processing. 
app.UseStaticFiles(new PathString("/app-Assets"));
// to allow access files not in wwwroot
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), @"Assets")),
    RequestPath = new PathString("/app-Assets")
});
app.UseRouting();
......

错误尝试方案及问题

曾尝试在MiddlewareApp的Program文件中通过UseFileServer配置转发静态文件:

...
app.UseFileServer(
    new FileServerOptions
    {
         FileProvider = new PhysicalFileProvider(@"\\https:\\localhost:7000\app-Assets"),
         // this is url of  static file in Main app
         RequestPath = new PathString("/app-Assets"),
         EnableDirectoryBrowsing = false
    });
...

前端通过以下方式访问:

<img src="https://localhost:7001/app-Assets/myImage.jpg">

预期请求会经MiddlewareApp的UseFileServer访问MainApp的静态文件,但抛出错误:

System.IO.DirectoryNotFoundException: '//https://localhost:7000/app-Assets/'

只有使用本地路径{LocalDrive}/app-Assets/时才能正常工作,显然这种方式无法跨服务器访问MainApp的静态文件。

可行解决方案:接口转发

放弃UseFileServer,通过接口实现静态文件的转发,代码如下:

[Route("GetImage")]
[HttpGet]
public async Task<IActionResult> Get(string filePath, bool inline = true)
{
    if (string.IsNullOrWhiteSpace(filePath))
        throw new ArgumentNullException(nameof(filePath));

    filePath = Path.Combine("app-Assets\\", filePath);

    var httpClient = _httpClientFactory.CreateClient("AnotherServerDirectory");
    var response = await httpClient.GetAsync(filePath);
    var ms = new MemoryStream(await response.Content.ReadAsByteArrayAsync());
    var ext = Path.GetExtension(filePath).ToLowerInvariant();

    var cd = new ContentDisposition
    {
        Inline = inline // false = prompt the user for downloading;  true = browser to try to show the file inline
    };

    Response.Headers.Add("Content-Disposition", cd.ToString());
    return new FileStreamResult(ms, GetMimeTypes()[ext]);
} 

通过Content-Disposition控制图片是直接显示还是下载,前端访问方式改为:

<img src="https://localhost:7001/GetImage?filePath=myImage.jpg">

内容的提问来源于stack exchange,提问作者Mohamed Elkordy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:05:14