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

然后新增 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM