netcore跨域Cors找不到"Access-Control-Allow-Origin"

原文:net core 3.1 跨域 Cors 找不到 “Access-Control-Allow-Origin”

ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("any", builder =>
        {
            //builder.AllowAnyOrigin() //允许任何来源的主机访问
            builder.WithOrigins("http://*.*.*.*") //.SetIsOriginAllowedToAllowWildcardSubdomains()//设置允许访问的域
                .AllowAnyMethod().AllowAnyHeader().AllowCredentials(); //
        });
    });
    services.AddControllers();
}

新增CorsMiddleware类

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);
    }
}

Configure中使用中间件

 app.UseMiddleware<CorsMiddleware>();
posted @ 2020-03-20 15:21  少年。  阅读(854)  评论(0编辑  收藏  举报