Angular调用ASP.NET Core API出现404未找到问题求助
问题描述
尝试从Angular前端向ASP.NET Core后端发起API调用时,遇到404未找到错误。
相关代码及错误信息
ASP.NET Core的CustomerController代码
[ApiController] [Route("api/[controller]")] public class CustomerController : ControllerBase { private readonly OrderManagmentContext _context; public CustomerController(OrderManagmentContext context) { _context = context; } [HttpPost("saveCustomer")] public async Task<ActionResult<CustomerDto>> saveCustomer(CustomerDto customer) { var entity = new Customer { Name = customer.Name, LastName = customer.LastName, City = customer.City, Company = customer.Company, EMail = customer.EMail, Id = customer.Id, Phone = customer.Phone, PostalCode = customer.PostalCode, Street = customer.Street, }; _context.Customers.Add(entity); await _context.SaveChangesAsync(); return customer; } }
Angular的CustomerService及保存按钮代码
saveCustomer(customer: CustomerDto) { const headers = { 'content-type': 'application/json' } const body = JSON.stringify(customer); return this.http.post<CustomerDto>(this.baseUrl + 'api/customer/savecustomer', body, { headers });} async addCustomer() { const dto = {} as CustomerDto; Object.assign(dto, this.formGroup.value); await firstValueFrom(this.customerService.saveCustomer(dto)); }
网页端错误信息
ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"https://localhost:44405/api/customer/savecustomer","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://localhost:44405/api/customer/savecustomer: 404 Not Found","error":"\n<html lang="en">\n\n<meta charset="utf-8">\nError\n\n\n
Cannot POST /api/customer/savecustomer\n\n\n"}
Postman错误信息
Error: connect ECONNREFUSED 127.0.0.1:44405
问题排查及解决方案
结合报错和代码,核心问题集中在以下几点:
后端服务未启动或端口不匹配
Postman返回ECONNREFUSED,说明后端服务并未在44405端口运行。- 检查ASP.NET Core项目启动日志,确认实际运行的端口(比如默认HTTPS端口可能是
44300而非44405)。 - 核对Angular中
baseUrl的配置,确保与后端实际地址、端口完全一致。
- 检查ASP.NET Core项目启动日志,确认实际运行的端口(比如默认HTTPS端口可能是
路由大小写不一致
后端Action路由为saveCustomer(驼峰格式),但前端请求的是savecustomer(全小写)。尽管ASP.NET Core默认路由大小写不敏感,但部分环境配置可能导致匹配失败,建议统一路径大小写,将前端请求路径改为this.baseUrl + 'api/customer/saveCustomer'。请求体参数绑定问题
后端Action未明确指定参数来源,可能导致模型绑定失败。给CustomerDto参数添加[FromBody]特性,明确从请求体获取数据:public async Task<ActionResult<CustomerDto>> saveCustomer([FromBody] CustomerDto customer)CORS配置缺失
若后端未配置跨域资源共享(CORS),也可能引发类似404的间接报错。在Program.cs中添加CORS配置:builder.Services.AddCors(options => { options.AddPolicy("AllowAngular", policy => policy.WithOrigins("http://localhost:4200") // 替换为Angular实际运行地址 .AllowAnyHeader() .AllowAnyMethod()); }); // 确保该代码放在app.UseRouting()之后,app.UseAuthorization()之前 app.UseCors("AllowAngular");全局路由前缀重复
检查Program.cs是否配置了全局路由前缀(如AddRoutePrefix("api")),若已配置会与Controller上的[Route("api/[controller]")]重复,导致路由变为api/api/customer/saveCustomer,需删除重复配置。
内容的提问来源于stack exchange,提问作者visCode

