1

I know that httpclient should be reused, but i'm curious if the same rules apply to the other objects used in this method specifically the JsonSerializer object when deserializing.

public async Task<T> PostAsync<T>(string actionName, object postData)
{
    try
    {
        var request = new HttpRequestMessage(HttpMethod.Post, new Uri(actionName));
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        request.Content = new StringContent(postData.ToString(), Encoding.UTF8, "application/json");

        var newClient = _httpClientFactory.CreateClient();
        newClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenModel.Token);

        var result = await newClient.PostAsync(request.RequestUri, request.Content);

        using (var streamReader = BuildNonClosingStreamReader(await result.Content.ReadAsStreamAsync()))
        using (var jsonReader = new JsonTextReader(streamReader))
        {
            JsonSerializer s = new JsonSerializer();
            return s.Deserialize<T>(jsonReader);
        }

    }
    catch (Exception)
    {

        throw;
    }
}
Airn5475
  • 2,452
  • 29
  • 51
Going-gone
  • 282
  • 1
  • 14
  • 1
    According to [Is the Json.NET JsonSerializer threadsafe?](https://stackoverflow.com/a/36189439), `JsonSerializer` is thread-safe, however it is mutable (it has many settings that can be modified) and there have been bugs regarding thread safety in the past (e.g. [here](https://github.com/JamesNK/Newtonsoft.Json/issues/1452)) so I don't really recommend sharing a single instance between threads. Beyond that, this question looks primarily opinion based. – dbc Aug 13 '20 at 16:42
  • For newtonsoft it does not appear that JsonConvert deserializes streams the same way as JsonSerializer. – Going-gone Aug 13 '20 at 18:58
  • `JsonConvert` eventually calls [`JsonSerializer.CreateDefault(JsonSerializerSettings)`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonSerializer_CreateDefault_1.htm) which takes the global serializer settings into account. There's also a subtle difference with the default value for [`CheckAdditionalContent`](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializer_CheckAdditionalContent.htm) where `JsonSerializer.Deserialize()` doesn't check for additional content unless explicitly told do, see [this answer](https://stackoverflow.com/a/37173878/3744182]). – dbc Aug 13 '20 at 19:02
  • 1
    Those are the differences of which I am aware. But your question was whether to create a `JsonSerializer` every time, not whether to deserialize from a stream vs from a string. – dbc Aug 13 '20 at 19:02

0 Answers0