在 ASP.NET Core 1.1 中,应用 CROS 时需要在启动文件中添加 CORS 中间件并配置策略。以下是代码示例:
首先,在 Startup.cs 文件中添加以下 using 语句:
using Microsoft.AspNetCore.Cors;
然后,在 Configure 方法中添加以下代码:
app.UseCors(builder => builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() );
这些方法将允许来自任何来源的请求,并允许使用任何HTTP头和方法。同时,还允许使用凭据(例如,使用身份验证)。
另外,如果您想使用特定的 CORS 策略,可以在 ConfigureServices 方法中添加以下代码:
services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://example.com")); });
然后,在 Configure 方法中调用该策略:
app.UseCors("AllowSpecificOrigin");
以上两种方法都可以解决在 ASP.NET Core 1.1 中应用 CORS 不按预期方式工作的问题。
上一篇:ASP.NETCore/EntityFramework-HTTPPostnotcreatingentitiesinjointablewhenusingmany-to-manyrelationship
下一篇:ASP.NETCore2.0.0AngularappshowingHTTPError502.5whenhostedonIIS