要解决ASP.NET Core Web API自定义路由不起作用的问题,可以尝试以下解决方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 添加路由服务
services.AddRouting();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// 配置自定义路由
endpoints.MapControllerRoute(
name: "customRoute",
pattern: "api/custom/{id}",
defaults: new { controller = "CustomController", action = "GetCustom" }
);
});
}
在上面的示例中,自定义路由的URL模式为"api/custom/{id}",并将其映射到名为"CustomController"的控制器的"GetCustom"操作。
[ApiController]
[Route("api/[controller]")]
public class CustomController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetCustom(int id)
{
// 处理逻辑
return Ok(result);
}
}
在上面的示例中,使用[Route]特性指定了控制器的路由前缀为"api/[controller]",并使用[HttpGet]特性指定了操作方法的HTTP GET请求路由为"{id}"。
通过以上步骤,您应该能够解决ASP.NET Core Web API自定义路由不起作用的问题。如果问题仍然存在,您可以检查其他可能的原因,例如路由顺序或控制器和操作方法的命名错误等。