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

ASP.NET Core 8.0部署至Azure App Service后,自定义静态文件CORS扩展失效问题求助

ASP.NET Core 8.0部署至Azure App Service后,自定义静态文件CORS扩展失效问题求助

我最近碰到一个特别棘手的CORS配置问题,想请大家帮忙排查下:

我在ASP.NET Core 8的应用里托管了一个带公式的Excel 365插件,为了让客户端能下载插件相关文件,我用app.UseStaticFiles()暴露了插件编译产物的存放目录。但这里有个问题:Excel公式插件需要通过JS从插件地址下载一个JSON文件,所以这个文件的响应必须带上正确的CORS头才行。

可惜ASP.NET Core本身不支持给静态文件请求指定CORS策略,于是我自己写了个扩展方法来解决这个问题:

public static class IApplicationBuilderExtensions
{
    /// <summary>
    /// In order for this to work, it must be called BEFORE UseCors is called in the startup.
    /// </summary>
    /// <param name="app"></param>
    /// <param name="policyName"></param>
    /// <param name="staticFileOptions"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseStaticFilesWithCors(this IApplicationBuilder app, string policyName, StaticFileOptions staticFileOptions)
    {
        app.UseWhen(context => context.Request.Path.StartsWithSegments(staticFileOptions.RequestPath), builder =>
        {
            builder.Use(async (ctx, next) =>
            {
                // Apply CORS policy to the request
                var corsService = ctx.RequestServices.GetRequiredService<ICorsService>();
                var corsPolicyProvider = ctx.RequestServices.GetRequiredService<ICorsPolicyProvider>();

                if (await corsPolicyProvider.GetPolicyAsync(ctx, policyName) is { } corsPolicy)
                {
                    var result = corsService.EvaluatePolicy(ctx, corsPolicy);
                    corsService.ApplyResult(result, ctx.Response);
                }

                await next();
            });
        });

        app.UseStaticFiles(staticFileOptions);
        return app;
    }
}

在Startup里我是这么用这个扩展的:

app.UseStaticFilesWithCors("API", new StaticFileOptions 
{ 
    FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(webroot), 
    RequestPath = new PathString("/o365addon") 
});

本地测试的时候不管是用IIS还是Kestrel跑,都完全正常——所有带Origin头且路径以/o365addon开头的请求,都能拿到正确的CORS允许头。可一旦把应用部署到Azure App Service上,这段代码就彻底失效了,响应里完全看不到CORS相关的头信息。

我翻遍了Azure App Service的配置项,只有API相关的板块提到了CORS设置,但我完全没用到那个配置。现在实在是没思路了,有没有大佬能给点排查方向或者解决建议?

补充说明:我已经严格按照扩展方法注释里的要求,确保UseCors()是在所有UseStaticFilesWithCors()调用之后才执行的,顺序上没问题。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 11:50:28