欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-10 21:39:58
首先在ConfigureServices添加 public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("any", builder => ......

首先在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>();

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