.net-core-2.2

.Net Core 2.2, PutAsync, HttpContent Question


I am transitioning from node with express to .Net Core 2.2. I'm trying to create a put request to push updates to an api. I've figured out I can create it with

var client = new HttpClient(); client.PutAsync(url, httpContent)

My first question is, how do I create the httpContent? Normally in this situation I would create a JSON object, but of course that won't work here.

My second question is, I'm using .Net Core 2.2. Is using the HttpClient the correct way or should I use the Factory?


Solution

  • Please refer to the following code snippet to make a post request, you can achieve the put request at the same, just change the method to Put.

    protected async Task<Tuple<HttpStatusCode, TOutput>> MakeRequest<TInput, TOutput>(string baseAdrress, string apiUrl, TInput data)
    {
        var contentData = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
    
        var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.BaseAddress = new Uri(baseAdrress);
    
        var response = await client.SendAsync(new HttpRequestMessage
        {
            RequestUri = new Uri(apiUrl, UriKind.Relative),
            Content = contentData,
            Method = HttpMethod.Post
        });
    
        if (response.StatusCode == HttpStatusCode.InternalServerError)
        {
            return Tuple.Create(HttpStatusCode.InternalServerError, default(TOutput));
        }
    
        var stringData = await response.Content.ReadAsStringAsync();
        var jsonData = JsonConvert.DeserializeObject<TOutput>(stringData);
    
        return Tuple.Create(HttpStatusCode.OK, jsonData);
    }
    

    Above code is just a quick demonstration for using http client, in real-world, you should use HttpClientFactory instead. There are multiple ways to use HttpClientFactory that you can read here at Microsoft Docs

    Using HttpClient directly can lead to some issues that was mentioned by M$ "As a first issue, while this class is disposable, using it with the using statement is not the best choice because even when you dispose HttpClient object, the underlying socket is not immediately released and can cause a serious issue named ‘sockets exhaustion’."