2

I have Web api method like below. The Web API is developed inClassic .Net 4.6.2

    [HttpPost]
    public async Task<IEnumerable<DocumentDTO>> GetDocuments([FromBody]IEnumerable<string> documentNames)
    {
        return await _domainService.GetDocuments(documentNames);
    }

Then I have ASP.Net Core client that was using HttpClient to post data. I have my own extension method that serializes the input using Newtonsoft.Json.JsonConvert and post it and then de-serializes the response

    public static async Task<TResult> MyPostMethodAsync<TSource, TResult>(this HttpClient httpClient, TSource source, string url)
    {
        // serialize the input
        var content = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(source)).ConfigureAwait(false);
        var stringContent = new StringContent(content, Encoding.UTF8, "application/json");

       //post json string
        var httpResponse = await httpClient.PostAsync(url, stringContent).ConfigureAwait(false);

        //ensures ok response
        httpResponse.EnsureSuccessStatusCode();

      // get response string
        var result = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

      //de-serialize the response
        return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<TResult>(result)).ConfigureAwait(false);
    }

The method above working fine. Note that its using PostAsync method.

Then I changed the above method to make use of PostAsJsonAsync extension method that is available in Microsoft.AspNet.WebApi.Client. So the new method looks like below

    public static async Task<TResult> MyPostMethodAsync<TSource, TResult>(this HttpClient httpClient, TSource source, string url)
    {
       // post as json
        var httpResponse = await httpClient.PostAsJsonAsync<TSource>(url, source).ConfigureAwait(false);

      // Ensures response is okay
        httpResponse.EnsureSuccessStatusCode();

       // get response string
        var result = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

        // de-seriazlize the response
        return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<TResult>(result)).ConfigureAwait(false);
    }

However the PostAsJsonAsync extension method does not post any data? The Web API Method always receive empty collection for documentnames parameter. (I'm also using my extension method to POST data to additional web api methods as well, but all POST methods receives null values or empty collection)

I am guessing its serialization/deserialization issue but I am not sure which serializer .Net 4.6.2 & .Net Core uses by default.

LP13
  • 30,567
  • 53
  • 217
  • 400
  • please show what is your 'Tsource source'. It works for me if I use List as source for example. – Set Sep 29 '16 at 12:08

0 Answers0