.NET Core Web API 跨域请求

使用.net core 3.0 搭建的Web API接口,用另一个服务器访问时候报这个错误:

 

解决方法如下:

1、在web api 项目的startup类的ConfigureServices方法中加入以下内容。

        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigins",
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:56003").AllowAnyHeader();
                    });
            });
        }    

2、在configure方法中加入以下内容,重新编译运行就可以了。

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            
            app.UseCors("AllowSpecificOrigins");
            
            app.UseStaticFiles();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }        

  

.NET Core Web API 跨域请求

上一篇:Yapi docker 数据卷的迁移


下一篇:WebApi使用Token(OAUTH 2.0方式)