[英]CORS is not working with .NET Core API and Angular frontend
我已經閱讀了類似的問題,嘗試了其中提到的幾個解決方案但沒有成功 - 問題很簡單,我真的不知道到底是什么地方錯了......
我有一個非常簡單的 .NET 核心 API,我想在其上設置 CORS。
我試過這種方式(端點路由): https://learn.microsoft.com/en-us/as.net/core/security/cors?view=as.netcore-5.0#enable-cors-with-endpoint-路由
Startup.cs 中的 ConfigureServices() 和 Configure() 方法
完全是默認生成的,只是添加了MSDN的CORS相關代碼。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "Policy1",
builder =>
{
// I read the site url from appsettings.json but for now I want to keep the example as simple as I can
// var lpSolverFrontendUrl = Configuration.GetValue<string>("Cors:AllowedSite");
builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("Policy1");
});
}
我的 controller class
[Route("[controller]/[action]")]
public class SimplexSolverController : Controller
{
public IActionResult Ping()
{
return Json(new { status = "OK" });
}
[HttpPost]
public IActionResult Solve([FromBody] LPModelDto lpModelDto)
{
bool wrongFormat = false;
string message = null;
SimplexSolutionDto solution = null;
//...
}
//...
}
我已經嘗試過的另一種方式(帶屬性): https://learn.microsoft.com/en-us/as.net/core/security/cors?view=as.netcore-5.0#enable-cors-with-屬性
Startup.cs這樣
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "Policy1",
builder =>
{
// I read the site url from appsettings.json but I want to keep the example as simple as I can
// var lpSolverFrontendUrl = Configuration.GetValue<string>("Cors:AllowedSite");
builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我的controller class這樣
我將EnableCors屬性放在 controller 方法上以在其上啟用 CORS。
[Route("[controller]/[action]")]
public class SimplexSolverController : Controller
{
public IActionResult Ping()
{
return Json(new { status = "OK" });
}
[EnableCors("Policy1")]
[HttpPost]
public IActionResult Solve([FromBody] LPModelDto lpModelDto)
{
bool wrongFormat = false;
string message = null;
SimplexSolutionDto solution = null;
//...
}
//...
}
無論我選擇哪種方式,我都會在 DevTools 控制台中收到錯誤消息,例如:從來源“http://localhost:4200”訪問“http://localhost:4000/simplexsolver/solve”中的 XMLHttpRequest 已被 CORS 策略阻止: 請求的資源上不存在“Access-Control-Allow-Origin”header。
我完全按照文章所說的進行操作,但沒有任何結果......感謝您的幫助!
更新
我終於成功啟用了CORS。 可悲的是,我無法在 ConfigureServices 中設置任何類型的策略,因為如果我這樣做,Access-Control-Allow-Origin header 將在預檢中具有“*”值(不是前端地址)請求的響應。 我使用的方式是:
現在我在 Startup.cs 中的兩個方法如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options => options.WithOrigins(Configuration.GetValue<string>("Cors:AllowedSite")).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
謝謝你給我的所有答案。 我希望這會在將來幫助某人。 但是我仍然很奇怪將 CORS 與策略一起使用有什么問題。
將您的代碼修復為:
app.UseCors("Policy1");
services.AddCors(options =>
{
options.AddPolicy("Policy1",
builder =>
{
.builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
並刪除
[EnableCors("Policy1")]
從 controller 動作。
我能夠在 .NET Core 3.1 中像這樣全局地允許 CORS :
Startup.cs 代碼:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: "AllowCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowCORS");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
用這個:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
//...
}
如果它不起作用,請將 Mvc 兼容版本設置為 3.0 使用
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
像這樣:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
//...
}
我需要在配置中更改調用 app.UseCors("CORS_POLICY") 的順序。
無效:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureMetrics();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseUserContextClaimsInjector();
app.UseGlobalExceptionHandlerMiddleware();
app.UseResponseCompression();
app.UseSwagger();
app.UseSwaggerUI();
app.UseStaticFiles();
app.ConfigureHealthCheck();
app.UseResponseCompression();
app.UseCors("CORS_POLICY");
作品:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CORS_POLICY");
app.ConfigureMetrics();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseUserContextClaimsInjector();
app.UseGlobalExceptionHandlerMiddleware();
app.UseResponseCompression();
app.UseSwagger();
app.UseSwaggerUI();
app.UseStaticFiles();
app.ConfigureHealthCheck();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.