且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

返回类型为HttpResponseMessage时,Web Api Get()路由不起作用

更新时间:2023-02-15 11:27:58

找到了原因!我已经按照有效的模板创建了一个空白的api控制器.提示一些复制/粘贴以缩小原因.这很微妙,我发布的代码也能正常工作,因为我更改了要公开发布的变量名,这最终是问题的原因.走吧.

Found the cause! I had created a blank api controller as per the template which worked. Cue a bit of copy/pasting to narrow down the cause. It's subtle and the code that I posted worked because I changed the variable names for posting publicly - which was ultimately the cause of the issue. Go figure.

要复制,请按照正常方式创建模板.这将创建一个方法;

To replicate, create your template as per normal. This will create a method;

public string Get(int id)

将此更改为;

public string Get(int personID)

并尝试运行.您将收到上述错误.似乎Get/Post/etc参数的声明必须与路由中指定的声明匹配.如果像我一样将参数更改为"personID",则可以通过将参数重命名为默认的"id"或使用更新名称修改路由来解决此问题;

And try to run. You'll get the error described as above. It seems that the declaration of the Get/Post/etc parameters MUST match that specified in the routing. If you change the parameter to "personID" as I did, you can fix by either renaming your parameter back to the default "id" or modifying your routing with the updating name;

config.Routes.MapHttpRoute(
    name: "ControllerAndId",
    routeTemplate: "api/{controller}/{personID}",
    defaults: null,
    constraints: new { personID = @"^\d+$" } // Only integers 
);

请注意routeTemplate和约束参数中的"{personID}".此字段的名称必须与您的参数名称匹配.在查找如何下载文件或仅查看Web API时,它从未在文档中真正说过这一点.在深入探讨路由/mvc时,可能会这样做,但是我不得不说,这很容易使不熟悉的n00b跳闸.请注意,我经验丰富的同事也没有发现:-).我希望这可以帮助其他痛苦的人!

Note the "{personID}" in the routeTemplate and constraint parameters. The name of this field MUST match that of the name of your parameter. It never actually says this in the doc when looking up how to download files or just generally looking at web api. It probably does when going into a high level of detail on routing/mvc but I have to say that this easily trips up a n00b not familiar with either. Mind you, my more experienced collegues didn't spot this either :-). I hope this helps others with the same pain!