ASP.NET Core API所有路由返回404错误的排查求助
我正在构建一个ASP.NET Core简易API,所有路由均返回404错误。OrderController已正确定义HTTP动词(GET、POST、PUT、DELETE)及路由,但API请求无法正常命中控制器动作。
OrderController代码
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using System.Collections.Generic; using System.Threading.Tasks; using TmbApplication.Models; using TmbApplication.Services; namespace TmbApplication.Controllers { [Route("api/[controller]")] [ApiController] public class OrderController(IOrderService orderService) : ControllerBase { private readonly IOrderService _orderService = orderService; [HttpGet] [ApiExplorerSettings(GroupName = "v1")] [ProducesResponseType(200, Type = typeof(IEnumerable<Order>))] [ProducesResponseType(500)] public async Task<ActionResult<IEnumerable<Order>>> GetOrders() { var orders = await _orderService.GetAllOrdersAsync(); return Ok(orders); } [HttpGet("{id}")] [ApiExplorerSettings(GroupName = "v1")] [ProducesResponseType(200, Type = typeof(Order))] [ProducesResponseType(404)] [ProducesResponseType(500)] public async Task<ActionResult<Order>> GetOrder(Guid id) { var order = await _orderService.GetOrderByIdAsync(id); if (order == null) { return NotFound(); } return Ok(order); } [HttpPost] [ApiExplorerSettings(GroupName = "v1")] [ProducesResponseType(201, Type = typeof(Order))] [ProducesResponseType(400)] [ProducesResponseType(500)] public async Task<ActionResult<Order>> CreateOrder([FromBody] Order order) { if (order == null) { return BadRequest("Invalid data."); } var createdOrder = await _orderService.CreateOrderAsync(order); return CreatedAtAction(nameof(GetOrder), new { id = createdOrder.Id }, createdOrder); } [HttpPut("{id}")] [ApiExplorerSettings(GroupName = "v1")] [ProducesResponseType(204)] [ProducesResponseType(400)] [ProducesResponseType(404)] [ProducesResponseType(500)] public async Task<ActionResult> UpdateOrder(Guid id, [FromBody] Order order) { if (id != order.Id) { return BadRequest("Order ID mismatch."); } var existingOrder = await _orderService.GetOrderByIdAsync(id); if (existingOrder == null) { return NotFound(); } await _orderService.UpdateOrderAsync(order); return NoContent(); } [HttpDelete("{id}")] [ApiExplorerSettings(GroupName = "v1")] [ProducesResponseType(204)] [ProducesResponseType(404)] [ProducesResponseType(500)] public async Task<ActionResult> DeleteOrder(Guid id) { var order = await _orderService.GetOrderByIdAsync(id); if (order == null) { return NotFound(); } await _orderService.DeleteOrderAsync(id); return NoContent(); } } }
Program.cs代码
using Microsoft.EntityFrameworkCore; using Microsoft.OpenApi.Models; using TmbApplication.Models; using TmbApplication.Services; using Microsoft.Extensions.DependencyInjection; using TmbApplication.Data; var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(options => { options.AddPolicy("AllowAll", policy => { policy.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql("DbConnection")); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Exemplo", Version = "v1" }); }); builder.Services.AddScoped<IOrderService, OrderService>(); builder.Services.AddControllers(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Exemplo v1"); }); } app.UseCors("AllowAll"); app.UseHttpsRedirection(); app.MapControllers(); app.Run();
已检查内容
- Program.cs中已包含
MapControllers() - 控制器路由配置正确(
[Route("api/[controller]")]) - 控制器已正确注册,Program.cs中包含
AddControllers()
Docker日志
2025-02-11 07:33:42 info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
2025-02-11 07:33:42 Request starting HTTP/1.1 GET http://localhost:3000/api/order/ - application/json 155
2025-02-11 07:33:42 info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
2025-02-11 07:33:42 Request finished HTTP/1.1 GET http://localhost:3000/api/order/ - 404 0 - 8.9322ms
2025-02-11 07:33:42 info: Microsoft.AspNetCore.Hosting.Diagnostics[16]
2025-02-11 07:33:42 Request reached the end of the middleware pipeline without being handled by application code. Request path: GET http://localhost:3000/api/order/, Response status code: 404
2025-02-11 07:33:47 info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
2025-02-11 07:33:47 Request starting HTTP/1.1 GET http://localhost:3000/swagger - application/json 155
2025-02-11 07:33:47 info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
2025-02-11 07:33:47 Request finished HTTP/1.1 GET http://localhost:3000/swagger - 404 0 - 0.4094ms
2025-02-11 07:33:47 info: Microsoft.AspNetCore.Hosting.Diagnostics[16]
2025-02-11 07:33:47 Request reached the end of the middleware pipeline without being handled by application code. Request path: GET http://localhost:3000/swagger, Response status code: 404
可能的原因及排查方向
1. 控制器程序集扫描问题
ASP.NET Core默认仅扫描启动项目程序集内的控制器,如果OrderController所在类库与启动项目分离,需手动指定扫描程序集:
builder.Services.AddControllers() .AddApplicationPart(typeof(OrderController).Assembly);
2. Docker端口映射错误
日志中请求地址为http://localhost:3000,需确认Docker容器是否将内部ASP.NET Core端口(默认80、5000或5001)正确映射到主机3000端口。端口不匹配会导致请求无法到达正确服务。
3. 路由大小写匹配问题
控制器路由为api/[controller],对应api/Order,但日志中请求的是api/order/(小写)。虽然ASP.NET Core默认路由大小写不敏感,但可尝试请求api/Order测试是否能命中路由,或检查是否手动开启了路由大小写敏感配置。
4. Swagger环境判断问题
日志中/swagger也返回404,说明Swagger中间件未正确加载。可暂时移除环境判断强制启用Swagger,验证是否能正常访问:
// 临时去掉环境判断 app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Exemplo v1"); });
5. Docker镜像构建问题
确认Docker镜像是否包含最新编译的控制器代码。若构建时未复制最新程序集,容器内运行的旧代码可能无有效路由。可重新构建镜像,或进入容器检查程序集文件是否存在。
内容的提问来源于stack exchange,提问作者Gabriel Braga Estefanski

