我正在尝试在我的ASP上启用跨起源资源共享。NET核心Web API,但我卡住了。

EnableCors属性接受字符串类型的policyName作为参数:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

policyName是什么意思,如何在ASP上配置CORS。NET核心Web API?


当前回答

如果你得到错误“没有'Access-Control-Allow-Origin'头是存在于所请求的资源。”特别是对于PUT和DELETE请求,您可以尝试在IIS上禁用WebDAV。

显然,WebDAVModule默认启用,默认禁用PUT和DELETE请求。

禁用WebDAVModule,添加到你的web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

其他回答

特别是在dotnet核心2.2中,你必须改变SignalR

.WithOrigins (http://localhost: 3000)或

.SetIsOriginAllowed(isOriginAllowed: _ => true) //所有源

用.AllowCredentials()代替。allowanyorigin ()

https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/

https://github.com/aspnet/AspNetCore/issues/4483

得到这个工作与。net Core 3.1如下

确保你把UseCors代码放在app.UseRouting()之间;和app.UseAuthentication ();

app.UseHttpsRedirection();

app.UseRouting();
app.UseCors("CorsApi");

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
    endpoints.MapControllers();
});

然后将此代码放在ConfigureServices方法中

services.AddCors(options =>
{
    options.AddPolicy("CorsApi",
        builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
            .AllowAnyHeader()
            .AllowAnyMethod());
});

在基本控制器上面我放了这个

[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

现在我所有的控制器都将继承BaseController,并启用CORS

对于Web API(ASP。Net core 6.0) 在Program.cs中,只需在builder.Build()之前添加;

builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

也添加

app.UseCors("corsapp");

注意“/”在最后-会阻塞CORS的原点

builder.WithOrigins("http://example.com/","http://localhost:55233/");

将阻止

use

builder.WithOrigins("http://example.com","http://localhost:55233"); 

如果你得到错误“没有'Access-Control-Allow-Origin'头是存在于所请求的资源。”特别是对于PUT和DELETE请求,您可以尝试在IIS上禁用WebDAV。

显然,WebDAVModule默认启用,默认禁用PUT和DELETE请求。

禁用WebDAVModule,添加到你的web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>