c# - ASP.NET 核心 : CORS headers only for certain static file types

标签 c# asp.net .net asp.net-core asp.net-core-mvc

我有一个 ASP .NET Core 自托管项目。我正在提供静态文件夹中的内容(没问题)。它可以毫无问题地跨站点提供图像(显示 CORS header )。但是,对于某些文件类型,例如 JSON,它们的 CORS header 不会显示,客户端站点也看不到内容。如果我将文件重命名为未知类型(例如 JSONX),它会使用 CORS header 提供服务,没问题。我怎样才能让这个东西为所有带有 CORS header 的东西提供服务?

我在 Startup.cs 中设置了以下 CORS 策略:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials() );
        });

        // Add framework services.
        services.AddMvc();
    }

下面是我的配置

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseCors("CorsPolicy");
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        // Static File options, normally would be in-line, but the SFO's file provider is not available at instantiation time
        var sfo = new StaticFileOptions() { ServeUnknownFileTypes = true, DefaultContentType = "application/octet-stream", RequestPath = "/assets"};
        sfo.FileProvider = new PhysicalFileProvider(Program.minervaConfig["ContentPath"]);
        app.UseStaticFiles(sfo);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

最佳答案

中间件可以帮助处理这种复杂的逻辑。我最近已经将它用于 JavaScript 源代码。看起来 JSON 的媒体类型是“application/json”。

/*
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

Made available under the Apache 2.0 license.
https://www.apache.org/licenses/LICENSE-2.0
*/

/// <summary>
/// Sets response headers for static files having certain media types.
/// In Startup.Configure, enable before UseStaticFiles with 
/// app.UseMiddleware<CorsResponseHeaderMiddleware>();
/// </summary>
public class CorsResponseHeaderMiddleware
{
    private readonly RequestDelegate _next;

    // Must NOT have trailing slash
    private readonly string AllowedOrigin = "http://server:port";


    private bool IsCorsOkContentType(string fieldValue)
    {
        var fieldValueLower = fieldValue.ToLower();

        // Add other media types here.
        return (fieldValueLower.StartsWith("application/javascript"));
    }


    public CorsResponseHeaderMiddleware(RequestDelegate next) {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Response.OnStarting(ignored =>
        {
            if (context.Response.StatusCode < 400 &&
                IsCorsOkContentType(context.Response.ContentType))
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", AllowedOrigin);
            }

            return Task.FromResult(0);
        }, null);

        await _next(context);
    }
}

关于c# - ASP.NET 核心 : CORS headers only for certain static file types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404940/

相关文章:

c# - 如何处理使用 CsvHelper 解析时的空列?

c# - EF Core 日志记录的内存泄漏

jquery - 我只从 asp.net Razor View 中获取 jQuery 中的第一个 id

javascript - 适用于 ASP.NET MVC 的 Google Maps JavaScript API 无法正常工作

c# - 如何使用泛型而不是继承来拥有多个版本的东西

c# - 计数排序 - 实现差异

c# - 无法将类型 'System.Int32' 转换为类型 'System.Object'。 LINQ to Entities 仅支持转换实体数据模型基元类型

c# - .NET 核心 Entity Framework - 转义 "@"字符

.net - .NET 的瑞典日历中没有 1712 年 2 月 30 日?

c# - wpf mvvm 等待方法在使用 await 任务延迟进行模拟时阻止 UI