Web API路由支持GUID和整数id

本文关键字:整数 id GUID 支持 API 路由 Web | 更新日期: 2023-09-27 18:04:04

如何同时支持GUID和integer的GET路由?我意识到guid并不理想,但它现在就是这样。我想添加对整数的支持,以便用户更容易记住和交流应该是唯一的"键"。"

示例路线:

testcases/9D9A691A-AE95-45A4-A423-08DD1A69D0D1   
testcases/1234

My WebApiConfig:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    var routes = config.Routes;
    routes.MapHttpRoute("DefaultApiWithAction", 
        "Api/{controller}/{action}");
    routes.MapHttpRoute("DefaultApiWithKey",
        "Api/{controller}/{key}",
        new { action = "Get" },
        new { httpMethod = new HttpMethodConstraint(HttpMethod.Get), key = @"^'d+$" });
    routes.MapHttpRoute("DefaultApiWithId", 
        "Api/{controller}/{id}", 
        new { action = "Get" }, 
        new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
    routes.MapHttpRoute("DefaultApiGet", 
        "Api/{controller}", 
        new { action = "Get" }, 
        new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
    routes.MapHttpRoute("DefaultApiPost", 
        "Api/{controller}", 
        new { action = "Post" }, 
        new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}

我的控制器(仅限方法签名):

[RoutePrefix("Api/TestCases")]
public class TestCasesController : PlanControllerBase
{
    [Route("")]
    public OperationResult<IEnumerable<TestCaseDTO>> Get([FromUri] TestCaseRequest request)
    [Route("{id}")]
    [HttpGet]
    public OperationResult<TestCaseDTO> Get(Guid id)
    [Route("{key}")]
    [HttpGet]
    public OperationResult<TestCaseDTO> Get(int key)
    ...
}

我得到一个内部服务器错误当我试图使用整数调用资源。任何帮助都是感激的!

Web API路由支持GUID和整数id

感谢@SirwanAfifi!我在ASP中遇到了属性路由。你提到的SO问题中提到的NET文章,但显然我当时没有看到路由属性约束的需要。

对我来说,在我的控制器方法上使用[Route("{id:guid}")][Route("{key:int}")]是有效的。我还在我的WebApiConfig中注释了与{id}{key}相关的Http路由,以验证控制器中的属性负责执行路由。