在ASP.NET Core中,API命名是指控制器(Controller)和动作方法(Action)的路由命名约定,它决定了客户端如何访问你的API端点。
原因:控制器或动作方法的路由属性配置不正确。
解决方案:
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// GET api/products
[HttpGet]
public IActionResult GetAll() { /*...*/ }
// GET api/products/5
[HttpGet("{id}")]
public IActionResult GetById(int id) { /*...*/ }
}
原因:多个动作方法具有相同的HTTP方法和路由。
解决方案:
[HttpGet("by-name/{name}")]
public IActionResult GetByName(string name) { /*...*/ }
[HttpGet("by-id/{id}")]
public IActionResult GetById(int id) { /*...*/ }
原因:未遵循RESTful命名约定。
解决方案:
原因:路由模板配置不当导致URL生成错误。
解决方案:
// 使用属性路由
[Route("api/v{version:apiVersion}/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet("{userId:int}")]
public IActionResult GetUser(int userId) { /*...*/ }
}
原因:在区域中使用API时路由配置不正确。
解决方案:
[Area("Admin")]
[Route("api/admin/[controller]")]
public class AdminProductsController : ControllerBase
{
// api/admin/products
[HttpGet]
public IActionResult GetAll() { /*...*/ }
}
MapControllers
时检查路由表:app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGet("/debug/routes", async context =>
{
await context.Response.WriteAsync(string.Join("\n", endpoints.DataSources.SelectMany(ds => ds.Endpoints)));
});
});
通过以上方法和最佳实践,你应该能够解决ASP.NET Core API命名中的常见问题。
没有搜到相关的文章