ASP.NET Core 3.1 快速实现跨域访问

2020年4月3日 5520点热度 7人点赞 0条评论
内容纲要

Startup 中,添加一个变量

        readonly string ganweiCosr = "AllowSpecificOrigins";

Startup.ConfigureServices 中,添加服务

#if CORS
            services.AddCors(options =>
            {
                options.AddPolicy(ganweiCosr,
                builder => builder.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin());
            });
#endif

中间件中,有两处地方要修改


            app.UseRouting();

#if CORS
            app.UseCors(ganweiCosr);
#endif

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
#if CORS
                endpoints.MapControllers().RequireCors(ganweiCosr);
#else
                endpoints.MapControllers();
#endif
            });

通过上面代码,即可实现全局跨域。

痴者工良

高级程序员劝退师

文章评论