You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular/C#项目中Access-Control-Allow-Origin跨域问题求助

问题分析与解决方案

核心问题

你遇到的错误包含两个关键问题:

  1. 404状态码:请求的接口路径https://localhost:7218/api/User/Login不存在或路径配置错误
  2. CORS头缺失:后端CORS中间件的执行顺序配置错误,导致跨域响应头未正确返回

具体修复步骤

1. 修正后端C#中间件顺序

ASP.NET Core中间件的执行顺序直接影响功能生效,UseCors必须放在UseRouting之后、UseEndpoints之前,同时要在UseStaticFiles之后。修改后的代码如下:

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseStaticFiles();
app.UseRouting();

// 关键:UseCors必须放在UseRouting之后、UseEndpoints之前
app.UseCors("localhost");

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireCors("localhost");
});

2. 检查并修正接口路径

404状态码说明接口地址可能有误,请确认:

  • UserController上是否添加了路由特性,比如[Route("api/[controller]")]
  • Login方法是否标记了[HttpPost("Login")],确保完整路径为api/User/Login

3. 修正Angular请求代码

  • 不要在请求头中添加Access-Control-Allow-Origin:这是后端返回的响应头,不是前端请求需要带的
  • 登录请求的Content-Type应使用application/json,而非application/text
  • 无需手动发送OPTIONS请求,Angular会自动处理跨域预检

修改后的Angular代码:

// 正确设置请求头(Angular默认也会自动处理application/json,可省略)
public headers = new HttpHeaders()
  .set('content-type', 'application/json');

Login(){
  this.http.post("https://localhost:7218/api/User/Login", 
    new LoginDto(this.login, this.password), 
    { headers: this.headers }
  ).subscribe(response => console.log(response))
}

4. 额外验证步骤

  • 启动后端后,用Swagger或Postman直接访问https://localhost:7218/api/User/Login,确认接口能正常返回(不再是404)
  • 确认前端LoginDto的字段结构和后端接收的模型完全一致,避免序列化错误

内容的提问来源于stack exchange,提问作者Jonatan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:10:11