c# ASP.NET Core2.2利用中间件支持跨域请求

时间:2023-12-09 18:58:19

1、public void Configure(IApplicationBuilder app, IHostingEnvironment env)方法里面

不要加上:app.UseCors();

2、上面方法加上:

app.UseMiddleware<CorsMiddleware>();

3、中间代码如下:

public class CorsMiddleware
{
    private readonly RequestDelegate next;

public CorsMiddleware(RequestDelegate next)
    {
        this.next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
            context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
            context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
            context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

if (context.Request.Method.Equals("OPTIONS"))
            {
                context.Response.StatusCode = StatusCodes.Status200OK;
                return;
            }
        }

await next(context);
    }
}