Angular/C#项目中Access-Control-Allow-Origin跨域问题求助
问题分析与解决方案
核心问题
你遇到的错误包含两个关键问题:
- 404状态码:请求的接口路径
https://localhost:7218/api/User/Login不存在或路径配置错误 - 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
相关产品推荐
相关产品推荐

