我试图在ASP.NET核心应用程序中为特定的API控制器启用CORS。首先,我安装了NuGet包,并将其添加到我的.csproj中
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />然后,在我的ConfigureServices中添加以下内容
services.AddCors(options => {
options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});在此之后,如果我将它添加到我的Configure中,它就会工作:
app.UseCors("AllowAll");然而,这为所有控制器启用了CORS。我只想为SessionApiController启用它。如果我将EnableCorsAttribute添加到控制器中:
[Route("api/session")]
[EnableCors("AllowAll")]
[ApiController]
public class SessionApiController : Controller {
[...]
[Route("init")]
public JsonResult InitSession() {
[...]
}
}..。它不起作用,当我试图访问/api/session/init端点时,Chrome给了我一个CORS错误(“请求的资源上没有‘访问-控制-允许-原产地’报头”)。我在这里错过了什么?
发布于 2019-08-27 12:47:00
考虑到以下ASP.NET核心WebApp:
App.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
</ItemGroup>
</Project>Startup.cs提取液
public void ConfigureServices(IServiceCollection services) {
services.AddCors(options => {
options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseCors(); // Doesn't work
//app.UseCors("AllowAll"); // Works
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}从要在其中应用AllowAll策略的控制器中提取:
[EnableCors("AllowAll")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase为了在其中正确应用CORS,需要将以下更改应用到代码中,如迁移MS文档中所述
Microsoft.AspNetCore.Cors。这将导致您的.csproj如下所示:netcoreapp3.0
Startup#Configure如下所示:
在netcoreapp2.2中(IApplicationBuilder app,IWebHostEnvironment env) { app.UseRouting();// AFAIK这不是使用属性的CORS所必需的。//这是必需的,因为如果不给//默认的CORS策略应用app.UseCors();if (env.IsDevelopment()) { app.UseDeveloperExceptionPage();} app.UseHttpsRedirection();app.UseAuthorization();app.UseEndpoints(端点=> { endpoints.MapControllers();});}app.UseEndpoints(端点=>{endpoints.MapControllers();});}app.UseEndpoints(端点=>{endpoints.MapControllers();});}https://stackoverflow.com/questions/57592654
复制相似问题