Tab*_*ock 4 cors reactjs asp.net-core asp.net-core-3.0
我正在尝试设置一个反应前端来与 .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();
}
Run Code Online (Sandbox Code Playgroud)
控制器类的属性:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]
Run Code Online (Sandbox Code Playgroud)
试试这个方法:
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.SetIsOriginAllowed(isOriginAllowed: _ => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});
});
...
}
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
...
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
app.UseCors(MyAllowSpecificOrigins);
...
}
Run Code Online (Sandbox Code Playgroud)
编辑MyAllowSpecificOrigins你的cors名称
| 归档时间: |
|
| 查看次数: |
4740 次 |
| 最近记录: |