我一直在学习本教程:
https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi
验证正常。
但是,我在控制台中收到CORS异常:
跨域请求被阻止:同一起源策略不允许读取https://localhost:44351/api/todolist/处的远程资源。 (原因:CORS请求未成功)。
在startup.cs中,我更改了:
// builder.AllowAnyOrigin()// .AllowAnyMethod()// .AllowAnyHeader();
至:
builder.WithOrigins(“ http://localhost:4200”).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
这没有效果。
有人可以帮助我解决吗?
这里是startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddProtectedWebApi(Configuration);
// Creating policies that wraps the authorization requirements
services.AddAuthorization();
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
services.AddControllers();
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("default");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
我已经尝试了您尝试过的所有方法以及其他方法,并且在此项目中遇到了相同的问题。可以在官方文档中找到更多详细信息。根据官方文档中的说明,您之前尝试过的跨域解决方案都是可以实现的,而且我认为问题可能会出现在此示例项目中。如果重新创建演示,则不会出现此类问题。 https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
最后,我提出的建议是在门户网站上设置CORS
,然后我亲自对其进行了测试以解决此问题。
此外,如果需要跟踪问题的根源,建议使用数据包捕获方法进行分析,检查两个网站的请求标头,可以参考the document。