KMJ*_*sen 43 cors .net-core angular
我不确定我错过了什么,但似乎无法让我的 CORS 策略与 .NET Core 3.1 和 Angular 8 客户端一起使用。
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// ...
// Add CORS policy
services.AddCors(options =>
{
options.AddPolicy("foo",
builder =>
{
// Not a permanent solution, but just trying to isolate the problem
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
// Use the CORS policy
app.UseCors("foo");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Run Code Online (Sandbox Code Playgroud)
错误消息客户端:
Access to XMLHttpRequest at 'https://localhost:8082/api/auth/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)
虽然我是不正确的配置CORS(以下公认的答案与事实帮助做的)问题的根源是不相关的。对于其他上下文,该应用程序在使用 CLI 运行 API 和 Angular 应用程序时完全正常工作 - 我只是在将它们都部署到 Web 服务器后才遇到这个问题。
该“实际”的问题结束了被有关SQL连接,这是我唯一的添加平面文件错误日志的API和运行SQL Server跟踪发现,该应用程序无法连接到SQL在所有后发现的。
我通常希望这只会返回 500 并且我会在 10 秒内意识到这个问题 - 但是 CORS 错误配置意味着 500 实际上从未被返回,因为 CORS 中间件首先失败。 至少可以说这是非常令人沮丧的!. 然而,我想在这里补充一点,以防其他人发现自己处于这种情况,因为我“追错了兔子”,如果你愿意的话。 修复 CORS 配置后,我意识到实际问题与 CORS 完全无关。
参考:
https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785
Abo*_*zlR 32
先app.UseRouting();然后app.UseCors("foo");
更改您的Configure方法,如下所示:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting(); // first
// Use the CORS policy
app.UseCors("foo"); // second
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Run Code Online (Sandbox Code Playgroud)
它对我有用!
Was*_*eem 25
Web API 正在使用app.UseHttpsRedirection();CORS如果请求的客户端不https基于,则会导致问题。因此,为了与http客户端一起使用它,我们需要注释或删除该行。
这个问题不在于CORS,https 导致了这个问题,但抛出的错误是说它与 CORS。
小智 7
添加 Cors 服务时,请确保.SetIsOriginAllowed((host) => true)在.WithOrigins("http://localhost:4200")
services.AddCors(options => {
options.AddPolicy("mypolicy",builder => builder
.WithOrigins("http://localhost:4200/")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader());
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30389 次 |
| 最近记录: |