make a http request with a custom body as json and return a json response in csharp
Here's an example using HttpClient to make a POST request with a custom JSON body and return a JSON response:
main.cs
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
publicasyncTask<TResponse> PostAsync<TRequest, TResponse>(string url, TRequest request){
using (var httpClient = new HttpClient())
{
var jsonRequest = JsonSerializer.Serialize(request);
var content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
var jsonResponse = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
thrownew HttpRequestException($"Request failed with status code {response.StatusCode} and content: {jsonResponse}");
}
return JsonSerializer.Deserialize<TResponse>(jsonResponse);
}
}
806 chars
24 lines
You can then call this method like this:
main.cs
var request = new MyRequest
{
// set request properties};
var response = await PostAsync<MyRequest, MyResponse>("https://example.com/api/my-endpoint", request);
// response properties are now populated