在C# WebAPI中,可以使用以下路由技巧:
[Route("api/users/{id}")]
public IHttpActionResult GetUser(int id)
{
// logic to get user
}
[RoutePrefix("api/users")]
public class UsersController : ApiController
{
[Route("{id}")]
public IHttpActionResult GetUser(int id)
{
// logic to get user
}
}
[Route("api/users/{id:int}")]
public IHttpActionResult GetUser(int id)
{
// logic to get user
}
[Route("api/users/{id:int=1}")]
public IHttpActionResult GetUser(int id)
{
// logic to get user
}
[Route("api/users/{id}", Name = "GetUserById")]
public IHttpActionResult GetUser(int id)
{
// logic to get user
}
這些都是在C# WebAPI中使用的常見路由技巧,可以幫助更靈活地定義API的路由規則。