Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read JSON from a StringContent object in an ApiController?

I'm writing an API controller intended to receive and parse the contents of a JSON asynchronous post, and am unable to read the contents of the StringContent object in that post.

Here is the section from my API controller where I expect to see the value. The value arriving in the ApiController method is null. And the jsonContent value is an empty string. What I'm expecting to see is the contents of a JSON object.

public class ValuesController : ApiController
{
    // POST api/values
    public void Post([FromBody]string value)
    {
        HttpContent requestContent = Request.Content;
        string jsonContent = requestContent.ReadAsStringAsync().Result;

        // Also tried this per mybirthname's suggestion.
        // But content ends up equaling 0 after this runs.
        var content = Request.Content.ReadAsStreamAsync().Result.Seek(0, System.IO.SeekOrigin.Begin);
    }
}

here is my controller to show how it's being called.

[HttpPost]
public ActionResult ClientJsonPoster(MyComplexObject myObject)
{
    this.ResponseInfo = new ResponseInfoModel();
    PostToAPI(myObject, "http://localhost:60146", "api/values").Wait();
    return View(this.ResponseInfo);
}

And this is the posting method.

private async Task PostToAPI(object myObject, string endpointUri, string endpointDirectory)
{
    string myObjectAsJSON = System.Web.Helpers.Json.Encode(myObject);
    StringContent stringContent = new StringContent(myObjectAsJSON, Encoding.UTF8, "application/json");
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri(endpointUri);
        using (HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(endpointDirectory, stringContent).ConfigureAwait(false))
        {
            // Do something
        }
    }
}

I suspect something is wrong with the signature of the Post method inside the ApiController. But don't know how that should be changed. Thanks for your help.

like image 791
Ken Palmer Avatar asked Nov 03 '16 17:11

Ken Palmer


1 Answers

You are mixing async and sync calls which will lead to deadlocks.

Update controller to

[HttpPost]
public async Task<ActionResult> ClientJsonPoster(MyComplexObject myObject) {
    this.ResponseInfo = new ResponseInfoModel();
    await PostToAPI(myObject, "http://localhost:60146", "api/values");
    return View(this.ResponseInfo);
}

Also [FromBody] is used to force Web API to read a simple type from the request body.

Update Api

public class ValuesController : ApiController {
    // POST api/values
    [HttpPost]
    public async Task Post() {
        var requestContent = Request.Content;
        var jsonContent = await requestContent.ReadAsStringAsync();

    }
}
like image 93
Nkosi Avatar answered Sep 18 '22 07:09

Nkosi