【开发笔记系列(三)】配置跨域Cors
声明全局变量
readonly string Policy = "_Policy";
在ConfigureServices(IServiceCollection services)中配置:
services.AddCors(options =>
{
options.AddPolicy(Policy,
builder => builder.WithOrigins("http://*")
.WithHeaders(HeaderNames.ContentType, "x-custom-header") //头部类型
.WithMethods("PUT", "DELETE", "GET", "OPTIONS") //设置几种请求方式
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
在Configure(IApplicationBuilder app, IWebHostEnvironment env)注册:
app.UseCors(Policy);
注意的是管道中跨域注册,一要放在swagge,UseRouting之前。
再修改UseEndpoints
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
到目前已经解决了跨域问题。也不用在每个控制器上声明[Policy]