支持API和整数ID的Web API路由 [英] Web API Routes to support both GUID and integer IDs

查看:93
本文介绍了支持API和整数ID的Web API路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为GUID和整数同时支持GET路由?我意识到GUID并不理想,但是现在是这样.我想添加对整数的支持,以使用户更容易记住和传达 唯一的键".

How can I support GET routes for both GUID and integer? I realize GUIDs are not ideal, but it is what it is for now. I'm wanting to add support for integers to make it easier for users to remember and communicate what should be unique "keys."

示例路线:

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) });
}

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

My controller (method signatures only):

[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)

    ...
}

当我尝试使用整数调用资源时,出现内部服务器错误.感谢您的帮助!

I'm getting an Internal Server Error when I attempt to call the resource using the integer. Any help is appreciated!

推荐答案

谢谢@SirwanAfifi!我遇到了 ASP.NET中的属性路由文章,但显然我当时没有看到对路由属性约束的需要.

Thank you to @SirwanAfifi! I had come across the Attribute Routing in ASP.NET article referred to in the SO question you mentioned, but apparently I didn't see the need for route attribute constraints at the time.

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

For me, it was using [Route("{id:guid}")] and [Route("{key:int}")] on my controller methods that did the trick. I also commented out the Http routes related to {id} and {key} in my WebApiConfig to verify that the attributes in the controller are responsible for doing the routing.

这篇关于支持API和整数ID的Web API路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆