查看 CORS 错误,但您获得数据并且它是可见的 C# (ASP .Net Core)
views CORS error, but you get data and it is visible C# (ASP .Net Core)
我的 Startup
方法中有这个配置,显然一切正常
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseCors("MyPolicy");
app.UseRouting();
app.UseAuthorization();
但是当我开始用另一个未注册的 url 做测试时,请求显示 cors 错误但同时显示响应,所以这是否意味着我 运行 我的服务没有被注册?
在此屏幕截图中,您可以看到我向其发出请求的url
保护我的 API 的正确做法是什么?我还读到浏览器将始终执行请求,即使它不可见
非常感谢您阅读我,我是新手
Configure 和 ConfigureService 中的 dot.net 代码是正确的。尝试允许任何方法并删除来源。看看你能不能用 postman
到达终点
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
首先,url是http://localhost:44344
,所以你需要将它添加到WithOrigins
中。并且你需要确保请求的方法类型包含在WithMethods("PUT", "GET")
。还有,你最好把app.UseCors("MyPolicy");
放在app.UseRouting();
和app.UseAuthorization();
之间。
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:44344")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("MyPolicy");
app.UseAuthorization();
在那种情况下,浏览器将始终执行请求,这就是它的工作原理。
作为 CORS 之外的一个选项,您可以添加主机过滤。只需将以分号分隔的主机名列表添加到 appsettings.json
{
...
"AllowedHosts": "example1.com;example2.com;localhost"
}
同样从 ASP.NET Core 5 Kestrel
服务器开始也支持主机过滤 - link
我的 Startup
方法中有这个配置,显然一切正常
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseCors("MyPolicy");
app.UseRouting();
app.UseAuthorization();
但是当我开始用另一个未注册的 url 做测试时,请求显示 cors 错误但同时显示响应,所以这是否意味着我 运行 我的服务没有被注册?
在此屏幕截图中,您可以看到我向其发出请求的url
保护我的 API 的正确做法是什么?我还读到浏览器将始终执行请求,即使它不可见
非常感谢您阅读我,我是新手
Configure 和 ConfigureService 中的 dot.net 代码是正确的。尝试允许任何方法并删除来源。看看你能不能用 postman
到达终点 options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
首先,url是http://localhost:44344
,所以你需要将它添加到WithOrigins
中。并且你需要确保请求的方法类型包含在WithMethods("PUT", "GET")
。还有,你最好把app.UseCors("MyPolicy");
放在app.UseRouting();
和app.UseAuthorization();
之间。
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:44344")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("MyPolicy");
app.UseAuthorization();
在那种情况下,浏览器将始终执行请求,这就是它的工作原理。
作为 CORS 之外的一个选项,您可以添加主机过滤。只需将以分号分隔的主机名列表添加到 appsettings.json
{
...
"AllowedHosts": "example1.com;example2.com;localhost"
}
同样从 ASP.NET Core 5 Kestrel
服务器开始也支持主机过滤 - link