使用HttpClient PostAsJsonAsync来调用我的API,如何正确接受API中的复杂类型?

时间:2016-08-22 15:42:41

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

我正在使用HttpClient来调用我的API。我正在构建一个对象并将其传递给PostAsJsonAsync,如下所示:

var foo = new Foo 
{
    //We will say these are the only two properties on the model:
    Id = 1,
    Name = "Test"
};

var response = await httpClient.PostAsJsonAsync("myApiPath/mytest", foo);

然后在我的API中,我试图获取foo对象并使用它做一些事情并返回HttpStatusCode这样的内容:

    [Route("mytest")]
    [HttpPost]
    public HttpResponseMessage MyTest<T>(T foo)
    {
        //Do some stuff, and return the status code
        return Request.CreateResponse(HttpStatusCode.OK);
    }

但是这不起作用,当我使用500时出现<T>错误。

为了确保我能够获得api并传递内容,我将foo更改为"someRandomString",然后在API中我将MyTest更改为仅接受像这样的字符串:public HttpResponseMessage MyTest(string someRandomString) { },并且工作正常。

如何让复杂类型正确传递到API?

1 个答案:

答案 0 :(得分:2)

控制器操作不应该是通用的:

[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest(Foo foo)
{
    //Do some stuff, and return the status code
    return Request.CreateResponse(HttpStatusCode.OK);
}

当然Foo类与客户端上的相同属性匹配。为了避免代码重复,您可以在一个单独的项目中声明您的合同,该项目将在您的Web和客户端应用程序之间共享。