[英]ASP.NET Core Swagger not working in Chrome with CORS error
我一直在使用 Swagger 关注 ASP.NET Web API 帮助页面的帮助,但在 Chrome 中收到以下错误:
它可以在 IE10 中运行,但似乎无法接受更改。
我发现以下条目Can't read swagger JSON from http://localhost:9000/api-docs/不幸的是,当它现在在 gulp 下工作时,它指的是在 grunt 下更改它。
我还尝试更改 ASP.NET 核心中的 CORS 设置:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// Inject an implementation of ISwaggerProvider with defaulted settings applied
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Status API",
Description = "A simple example ASP.NET Core Web API!",
TermsOfService = "None",
Contact = new Contact { Name = "A Persone", Email = "some-support@some-company.com", Url = "http://www.some-company.com/" },
License = new License { Name = "Use under LICX", Url = "http://url.com" }
});
});
services.AddCors(options =>
{
options.AddPolicy("AnyOrigin", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
app.UseCors("AnyOrigin");
}
不幸的是,这没有任何区别。
关于如何通过更改 gulp 设置或 .NET 更改来解决它的建议将非常受欢迎
通常这应该可以解决问题,您只需要它具有相同的策略名称。 如果要将过滤器应用于所有请求/路由,我认为没有必要添加过滤器。
// ConfigureServices
services.AddCors(options =>
{
options.AddPolicy("AnyOrigin", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod();
});
});
// Configure
app.UseCors("AnyOrigin");
// Register other middleware here, like UseMvc or UseStaticFiles, depending on if you
// want StaticFiles to be affected by cors or not you put it before or after the UseCors call
更新
就像上面评论中提到的,中间件是按照它们注册的顺序执行的。 该请求在 Cors 中间件收到之前到达您的 APi 控制器。
您的 Configure 方法必须如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
// it must be placed before UseMvc and before or after
// UseStaticFiles, depending on if you want the static files to be
// Cors enabled or not
app.UseCors("AnyOrigin");
app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.