启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

huangapple go评论53阅读模式
英文:

Enable CORS in Asp.Net Application

问题

我遇到了"访问http://localhost:60261/api/student/?Name=qwwertyqwe&Age=21的XMLHttpRequest来自http://localhost:4200的源已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'头。"

尽管API已被调用并按预期工作,但Chrome控制台中出现了错误。
我已经采取了以下措施。

  1. 我在API中安装了CORS NuGet包。

  2. 我尝试在WebAPIConfig.cs文件中添加EnableCorsAttribute和config.EnableCors,但仍然显示错误。

以下是Chrome截图:
启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

EnableCorsAttribute错误
启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

config.EnableCors错误
启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

英文:

I am getting "Access to XMLHttpRequest at 'http://localhost:60261/api/student/?Name=qwwertyqwe&Age=21' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Although the API is called and it is working as expected, but there is Error thrown at Chrome console.
Things I have done.

  1. I have install CORS nuget package in the API.

  2. I tried to add
    EnableCorsAttribute and config.EnableCors in WebAPIConfig.cs file
    but it is also showing error.

Below is the Chrome screenshot:
启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

**EnableCorsAttribute Error **
启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

**config.EnableCors Error **
启用 ASP.NET 应用程序中的跨域资源共享 (CORS)

答案1

得分: 1

将以下内容添加到你的 program.cs 文件或你的应用程序构建的位置:

var app = builder.Build();
...
app.UseCors(policy => policy.AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials()
                            .WithOrigins("https://localhost:4200"));

需要注意的是,UseCors() 需要在 UseAuthentication()UseAuthorization() 之前调用。

英文:

Add this to your program.cs or wherever your application is built

var app = builder.Build();
...
app.UseCors(policy => policy.AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials()
                            .WithOrigins("https://localhost:4200"));

Do note that the UseCors() needs to be called before UseAuthentication() and UseAuthorization()

答案2

得分: 0

[EnableCors("*", "*", "*")] 属性添加到您想要允许来自其他域的请求的 API 控制器或方法中。或者,在 WebAPIConfig.cs 文件中,您可以全局启用 CORS。

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
英文:

add the [EnableCors("", "", "*")] attribute to the API controller or method that you want to allow requests from other domains.
Or, In the WebAPIConfig.cs file, you can enable CORS globally.

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

huangapple
  • 本文由 发表于 2023年2月6日 18:10:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定