加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:14:41 所属栏目:asp.Net 来源:网络整理
导读:我没有在Stackoverflow上找到解决方案后解决了这个问题,所以我在这里分享我的问题和答案中的解决方案. 在使用AddCors的.NET Core Web Api应用程序中启用跨域策略后,它仍无法在浏览器中运行.这是因为浏览器(包括Chrome和Firefox)将首先发送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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读