ASP .NET Core:仅适用于某些静态文件类型的CORS标头 [英] ASP .NET Core: CORS headers only for certain static file types

查看:124
本文介绍了ASP .NET Core:仅适用于某些静态文件类型的CORS标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP .NET Core自托管项目.我正在从静态文件夹提供内容(没问题).它可以跨站点提供图像,而不会出现问题(显示CORS标头).但是,对于某些文件类型(例如JSON),它们不会显示CORS标头,并且客户端站点看不到内容.如果我将文件重命名为未知类型(例如JSONX),它将获得带有CORS标头的服务,这没有问题.我该如何使用CORS标头为所有内容提供服务?

I have an ASP .NET Core self-hosted project. I am serving up content from a static folder (no problem). It serves up images cross-site without issue (CORS header shows up). However, for some file types, such as JSON, they CORS headers don't show up, and the client site can't see the content. If I rename the file to an unknown type (such as JSONX), it gets served with CORS headers, no problem. How can I get this thing to serve everything with a CORS header?

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

I have the following CORS policy set up in my Startup.cs:

    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".

Middleware can help with this sort of complex logic. I've gotten this to work recently for JavaScript sources. It looks like the media-type for JSON is "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);
    }
}

这篇关于ASP .NET Core:仅适用于某些静态文件类型的CORS标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆