在 .NET Core Web API 上为 CORS 启用 OPTIONS 标头 [英] Enable OPTIONS header for CORS on .NET Core Web API

查看:36
本文介绍了在 .NET Core Web API 上为 CORS 启用 OPTIONS 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I solved this problem after not finding the solution on Stackoverflow, so I am sharing my problem here and the solution in an answer.

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

After enabling a cross domain policy in my .NET Core Web Api application with AddCors, it still does not work from browsers. This is because browsers, including Chrome and Firefox, will first send an OPTIONS request and my application just responds with 204 No Content.

推荐答案

向您的项目添加一个中间件类来处理 OPTIONS 动词.

Add a middleware class to your project to handle the OPTIONS verb.

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;

        public OptionsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext context)
        {
            return BeginInvoke(context);
        }

        private Task 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;
                return context.Response.WriteAsync("OK");
            }

            return _next.Invoke(context);
        }
    }

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

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

Then add app.UseOptions(); this as the first line in Startup.cs in the Configure method.

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

这篇关于在 .NET Core Web API 上为 CORS 启用 OPTIONS 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆