Search code examples
c#asp.net-web-apidotnet-httpclient

Using HttpClient PostAsJsonAsync to call my API, how do properly accept the complex type in the API?


I'm using HttpClient to call my API. I am building up an object and passing it in to the PostAsJsonAsync like this:

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

Then in my API I am trying to grab the foo object and do some stuff with it and return a HttpStatusCode like this:

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

But this doesn't work, I get a 500 error when I use <T>.

Just to make sure that I was able to get ahold of the api and pass something in I changed foo to "someRandomString" and then in the API I changed MyTest to just accept a string in like this: public HttpResponseMessage MyTest(string someRandomString) { } and that worked fine.

How can I get the complex type to get passed into the API properly?


Solution

  • The controller action should not be generic:

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

    where of course the Foo class matches the same properties that you have on the client. To avoid code duplication you could declare your contracts in a separate project that will be shared between your web and client applications.