我不确定我错过了什么,但似乎无法使我的CORS策略与.NET Core3.1和Angel8客户端一起工作.
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();
});
}
客户端错误消息:
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.
UPDATE:
虽然我错误地配置了CORS(下面的答案确实有帮助),但问题的根源是不相关的.另外,在使用CLI运行API和Angular应用程序时,该应用程序运行完全正常——我只是在将它们都部署到web服务器后才遇到这个问题.
这"actual"个问题最终与SQL连接有关,我只是在将平面文件错误日志(log)添加到API并运行SQL Server跟踪后发现该应用程序根本无法连接到SQL.
我通常认为这只会返回500,并且我会在10秒内意识到这个问题-然而,CORS的错误配置意味着实际上永远不会返回500,因为CORS中间件首先出现了故障.This was immensely frustrating to say the absolute least!美元.然而,我想在这里补充一下,如果其他人发现自己处于这种情况,就像我"追错了兔子",如果你愿意的话.After fixing the CORS configuration, I realized the actual issue was entirely unrelated to CORS.
TL;DR; - Sometimes "Non-CORS" .NET Server-side Errors Can Be Returned as CORS Errors If CORS policies Aren't Set Correctly
参考资料:
https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785个