POST 从 Chrome 到 .net core web api 的请求不工作

POST request to .net core web api from Chrome is not working

我正在做一个 .net 核心网络 api 项目,这个块让我做噩梦。我正在尝试将请求从 ionic-angular 发送到 .net 核心项目。 GET 请求运行良好。但是 POST 请求不是。当我尝试在 chrome 中测试项目时,它对 OPTIONS 请求说 net::ERR_CONNECTION_RESET。我了解 Chrome 在我真正的 POST 请求之前发送预检 OPTIONS 请求。但这就是问题所在。我试图用这样的中间件处理该 OPTIONS 请求

  

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Hosting;

    namespace A.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[] { "http://localhost:8100" });
                    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");
                }
                else
                {
                    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:8100" });
                    context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
                    context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
                }

            }
        }

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

  

但还是没有用。如果有什么技巧,请赐教!

Chrome 发送 OPTIONS 的原因是因为您的 .net 服务器位于另一个 URL(域),而不是制作 [=24] 的网页(组件) =].这是为了保护您免受使用 CORS - 跨源请求共享的跨源类型的攻击。

您可以在 Startup.cs:

中启用 CORS
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
          // All the other things here
           if (env.IsDevelopment()) // For development only, we allow CORS from anywhere.
            {
                app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials().Build());
            }
         }

您需要安装此软件包:Microsoft.AspNetCore.Cors

进一步阅读:https://docs.microsoft.com/en-us/aspnet/core/security/cors

为此,您必须在 chrome 浏览器中安装一个扩展程序,它会向服务器发送跨域请求。 Url 如下所示。

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

需要在WebAPIglobal.aspx中添加以下几行代码

 protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }