Web API路由支持GUID和整数ID

时间:2015-07-23 03:40:10

标签: c# asp.net-web-api asp.net-web-api-routing

如何为GUID和整数支持GET路由?我意识到GUID不是理想的,但它现在就是它。我想添加对整数的支持,以便用户更容易记住和传达应该唯一的键#34。

示例路线:

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

我的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)

    ...
}

当我尝试使用整数调用资源时,我收到内部服务器错误。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:21)

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

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