微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – ASP .NET Core:仅适用于某些静态文件类型的CORS标头

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

我在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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐