且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-15 20:01:21

中间件可以帮助您解决这种复杂的逻辑.我已经将此功能最近用于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);
    }
}