英文:
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控制台中出现了错误。
我已经采取了以下措施。
-
我在API中安装了CORS NuGet包。
-
我尝试在WebAPIConfig.cs文件中添加EnableCorsAttribute和config.EnableCors,但仍然显示错误。
英文:
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.
-
I have install CORS nuget package in the API.
-
I tried to add
EnableCorsAttribute and config.EnableCors in WebAPIConfig.cs file
but it is also showing error.
Below is the Chrome screenshot:
答案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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论