Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET Core: CORS headers only for certain static file types

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?

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();
    }

And the following is my Configure

    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?}");
        });
    }
like image 735
Blake Avatar asked Nov 09 '22 06:11

Blake


1 Answers

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);
    }
}
like image 70
LexH Avatar answered Nov 14 '22 22:11

LexH