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

前端之家收集整理的这篇文章主要介绍了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();
}
原文链接:https://www.f2er.com/netcore/247661.html

猜你在找的.NET Core相关文章