asp.net-core – 在.NET Core Web API上为CORS启用OPTIONS标头

我没有在Stackoverflow上找到解决方案后解决了这个问题,所以我在这里分享我的问题和答案中的解决方案.

在使用AddCors的.NET Core Web Api应用程序中启用跨域策略后,它仍无法在浏览器中运行.这是因为浏览器(包括Chrome和Firefox)将首先发送OPTIONS请求,而我的应用程序只响应204 No Content.

解决方法

在项目中添加一个中间件类来处理OPTIONS动词.
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;

namespace Web.Middlewares
{
    public class OptionsMiddleware
    {
        private readonly RequestDelegate _next;
        private IHostingEnvironment _environment;

        public OptionsMiddleware(RequestDelegate next,IHostingEnvironment environment)
        {
            _next = next;
            _environment = environment;
        }

        public async Task Invoke(HttpContext context)
        {
            this.BeginInvoke(context);
            await this._next.Invoke(context);
        }

        private async void BeginInvoke(HttpContext context)
        {
            if (context.Request.Method == "OPTIONS")
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin",new[] { (string)context.Request.Headers["Origin"] });
                context.Response.Headers.Add("Access-Control-Allow-Headers",new[] { "Origin,X-Requested-With,Content-Type,Accept" });
                context.Response.Headers.Add("Access-Control-Allow-Methods",new[] { "GET,POST,PUT,DELETE,OPTIONS" });
                context.Response.Headers.Add("Access-Control-Allow-Credentials",new[] { "true" });
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync("OK");
            }
        }
    }

    public static class OptionsMiddlewareExtensions
    {
        public static IApplicationBuilder USEOptions(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<OptionsMiddleware>();
        }
    }
}

然后添加app.USEOptions();这是Configure方法中Startup.cs的第一行.

public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory)
{
    app.USEOptions();
}

相关文章

本文将从上往下,循序渐进的介绍一系列相关.NET的概念,先从...
基于 .NET 的一个全新的、好用的 PHP SDK + Runtime: Pe...
.NET 异步工作原理介绍。
引子 .NET 6 开始初步引入 PGO。PGO 即 Profile Guided Opti...
前言 2021/4/8 .NET 6 Preview 3 发布,这个版本的改进大多来...
前言 开头防杠:.NET 的基础库、语言、运行时团队从来都是相...