返回类型为HttpResponseMessage时,Web Api Get()路由不起作用 [英] Web Api Get() route not working when return type is HttpResponseMessage

查看:226
本文介绍了返回类型为HttpResponseMessage时,Web Api Get()路由不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我有些头疼.最终,我试图返回图像,但是我一直在尝试并将其简化为使用字符串.

This is causing me a bit of a headache. Ultimately, I'm trying to return an image but I've been experimenting and simplified this to using a string.

我想要什么: 转到URL:

What I want: go to URL:

http://xxx/api/helloworld/1

回复:你好,世界!"

Responds with: "Hello world!"

以下Web api声明适用于提供的网址;

The following web api declarations work for the url supplied;

public string Get([FromUri]int id) { return "Hello World"; }
public Task<string> Get([FromUri]int id) { return "Hello World"; }

什么不起作用;

public HttpResponseMessage Get([FromUri]int id) 
{ 
    return Request.CreateResponse<string>(HttpStatusCode.OK, "Hello World");
}

public HttpResponseMessage Get([FromUri]int id)
{
    HttpResponseMessage response = new HttpResponseMessage();

    string text = "Hello World";
    MemoryStream test = new MemoryStream();
    test.Write(ConversionUtilities.ToBytes(text) /*custom string->byte[] method, UTF-8 encoding*/, 0, text.Length);

    response.Content = new StreamContent(test);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
    response.StatusCode = HttpStatusCode.OK;

    return response;
}

当我有一个具有返回类型HttpResponseMessage的Get()时,会发生以下错误;

What happens when I have a Get() with a return type of HttpResponseMessage is the following error is returned;

No HTTP resource was found that matches the request URI "http://xxx/api/helloworld/1"

此错误仅针对此特定的返回类型出现.现在,我在WebApiConfig.cs文件中的路由如下(并且适用于字符串"返回类型);

This error only appears for this particular return type. Now, my routing in the WebApiConfig.cs file is as follows (and works for "string" return types);

// Controller with ID
// To handle routes like "/api/VTRouting/1"
config.Routes.MapHttpRoute(
    name: "ControllerAndId",
    routeTemplate: "api/{controller}/{id}",
    defaults: null,
    constraints: new { id = @"^\d+$" } // Only integers 
);

// Controllers with Actions
// To handle routes like "/api/VTRouting/route"
config.Routes.MapHttpRoute(
    name: "ControllerAndAction",
    routeTemplate: "api/{controller}/{action}"
);

// Controller Only
// To handle routes like "/api/VTRouting"
config.Routes.MapHttpRoute(
    name: "ControllerOnly",
    routeTemplate: "api/{controller}"
);

有什么想法吗?我对返回类型的行为感到困惑:-S

Any thoughts? I'm stumped as to the return type behaviour :-S

推荐答案

找到了原因!我已经按照有效的模板创建了一个空白的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!

这篇关于返回类型为HttpResponseMessage时,Web Api Get()路由不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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