[英]Request is blocked by CORS policy
I am running a C# Controller locally and it is serving endpoint /api
.我在本地运行 C# Controller ,它正在服务端点/api
。 I have a local html page with Javascript trying to fetch data from that endpoint.我有一个本地 html 页面,其中 Javascript 试图从该端点获取数据。 But I see the console with this failure.但是我看到控制台失败了。
Access to fetch at 'https://localhost:44388/api' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略已阻止从源“null”获取“https://localhost:44388/api”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”header。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
In my C# controller project, in the Startup.cs, I already setup this in public void ConfigureServices(IServiceCollection services)
在我的 C# controller 项目的 Startup.cs 中,我已经在public void ConfigureServices(IServiceCollection services)
中设置了这个
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
and in public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
, I have put在public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
中,我放了
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
Can you please tell me what am I missing?你能告诉我我错过了什么吗?
Thank you.谢谢你。
Try to use this syntax尝试使用此语法
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
.....
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
// app.UseRouting();
app.UseCors("AllowAnyOrigin");
// app.UseAuthorization();
// app.UseEndpoints(..
}
Make sure that UseCors should be in the end of Configure method but before UseAuthorizaton.确保 UseCors 应该位于 Configure 方法的末尾,但在 UseAuthorizaton 之前。 AddCors should be at the top of Configure services. AddCors 应该位于配置服务的顶部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.