我正在尝试建立一个react前端来与.net后端进行通信。然而我似乎被cors设置卡住了。下面是我后端项目的启动代码以及我的前端代码。我按照多个指南进行操作,但不确定出了什么问题,这在我的本地主机上有效,但在部署到云上后无效。(我遵循的指南:https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 和 https://code-maze.com/enabling-cors-in-asp-net-core/)
感谢您的帮助!
React应用程序控制台中的错误: 从源'https://frontend.azurewebsites.net'访问'https://backend.azurewebsites.net/api/accountcredentials'被CORS策略阻止:预检请求的响应未能通过访问控制检查:所请求的资源上不存在'Access-Control-Allow-Origin'头信息。如果一个不透明响应可以满足您的需求,则将请求的模式设置为“no-cors”,以禁用CORS获取资源。
asp.net项目的启动代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddNewtonsoftJson();
services.AddSingleton<UserService>();
services.AddSingleton<AccountService>();
services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
{
builder.AllowAnyOrigin() //dev
//.WithOrigins("http://localhost:3007") // dev
//.WithOrigins("https://frontend.azurewebsites.net")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting(routes =>
{
routes.MapControllers();
});
app.UseCors("ReactPolicy");
app.UseAuthorization();
}
控制器类上的属性:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]