我正在尝试在应用程序启动时启用“*”CORS标头:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(opts =>
{
opts.Filters.Add(new AuthorizationFilterFactory());
});
services.AddCors(opts => opts.AddPolicy("*",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()));
services.AddSwaggerGen();
services.ConfigureSwaggerGen(opts =>
{
opts.SingleApiVersion(new Info { Version = "v1", Title = "CORS app" });
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("*");
app.UseSwagger();
app.UseSwaggerUi();
app.UseMiddleware(typeof(ExceptionHandlingMiddleware));
app.UseMvc();
}
标题未显示。试图从不同的域中使用Ajax请求我的资源,我得到了:
415(不支持的媒体类型)
尝试用JS:
$.post("http://example.com/some-api", JSON.stringify({"name": "hello"}));
有什么想法吗?中间件注册的顺序可能有问题吗?
更新:显然,此CORS库仅在识别XHR跨源请求时才添加标头。它突然开始为我工作。谢谢大家的意见。