JP *_*tra 5 c# .net-core asp.net-core
我有一个公共分析 Web api (.Net Core 3.1),它可以从我的各种 Web 应用程序和网站(页面视图等)捕获基本分析。我非常希望以更严格的方式配置 cors,因为我很清楚流量的来源。值得注意的是,我正在将此应用程序从 更新.Net Core 2.2为.Net Core 3.1.
Startup.cs我的文件中有以下方法
public void ConfigureServices(IServiceCollection services)
{
...
ConfigureCors(services);
}
private void ConfigureCors(IServiceCollection services)
{
// https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins(AppConfiguration.CorsOrigins)
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
Run Code Online (Sandbox Code Playgroud)
AppConfiguration是我用来处理配置的类,它json使用以下方式获取值:
public string[] CorsOrigins => _config["CorsOrigins"].Split(',');
在 中appsettings.Development.json,我有"CorsOrigins": "*"
我非常想在appsettings.Production.json和appsettings.Staging.json文件中指定严格的来源。
例如
,但在部署时,我会得到网站/应用程序点击各个端点时"CorsOrigins": "https://subdomain.example.com,https://www.example.com,https://example.com"的状态。502
"CorsOrigins": "*"Startup.cs在本地工作,因此据我所知,该文件不会有任何问题。
更新: "CorsOrigins": "*"实际上也不适用于临时或生产环境。现在我更困惑了。需要明确的是,这是一个cors问题。在升级到之前,以下工作正常.Net Core 3.1:
private void ConfigureCors(IServiceCollection services)
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
Run Code Online (Sandbox Code Playgroud)
抱歉,这是一个困难的问题,因此可能有很多原因导致它不起作用,但我遇到了类似的问题,并通过更改 Configure() 函数中的 cors 调用来解决它。配置()函数是在运行时被调用并充当http请求管道,因此在某些情况下执行顺序很重要(https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup?view =aspnetcore-3.1#配置方法)
您可以尝试以下操作:
改变电流:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("CorsPolicy"); //Move this line
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
Run Code Online (Sandbox Code Playgroud)
到:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy"); // Here
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
Run Code Online (Sandbox Code Playgroud)
因此,http 管道中的第一个操作是验证 cors。我认为这是一个公平的赌注,因为从您的问题来看,听起来您没有收到应用程序初始化错误,而是收到运行时客户端请求时间错误。我不确定这是否能解决问题,但也许有帮助!
| 归档时间: |
|
| 查看次数: |
945 次 |
| 最近记录: |