net core api 跨域 Cors 找不到 “Access-Control-Allow-Origin”

  public static void AddCorsSetup(this IServiceCollection services)
{

    services.AddCors(c =>
    {
               //允许任意跨域请求
                    c.AddDefaultPolicy(policy =>
                    {
                            policy
                            .SetIsOriginAllowed((host) => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                    });
    });


}

 

 

 public class CorsMiddleware
    {
        private readonly RequestDelegate _next;
        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }
            await _next(context);
        }
        // 使用 app.UseMiddleware<CorsMiddleware>();
    }

 

 

public static class UseCorsExtend
    {
        public static void UseCorsMiddleware(this IApplicationBuilder app) 
        {
            app.UseCors();
            app.UseMiddleware<CorsMiddleware>();
        }
    }

 

posted @ 2022-05-22 11:06  LuoCore  阅读(167)  评论(0编辑  收藏  举报