'C# HttpClient request API suite
I'm trying to develop an API suite so I can call it by passing some parameters. I successfully made the part about GET method. POST seems a bit more complicated and I didn't find any source so I can understand how to make it. My plan is to call in POST with a body as parameter
I didn't develop the API I'm going to POST but it's not even a public one but inside the project development. Using .NET core 5.0. The scope is to call some APIs as regression tests before any deploy from the dev team and some of them might return a data that will be used as body param in the next API so I'm developing a console app that check if everything is OK.
This is the GET request I developed, could you help me understand how to make it using POST method?:
static void Main(string[] args)
{
string url = ConfigurationManager.AppSettings["url"];
string jsonBody = "";
string method = "GET";
string result = CallApi(url, method, jsonBody);
}
public static string CallApi(string url, string method, string bodyInput)
{
string bodyOutput = null;
HttpClient client = new();
Uri uri = new(url);
switch (method)
{
case "GET":
Task<HttpResponseMessage> response = client.GetAsync(uri);
HttpResponseMessage result = response.Result;
HttpContent content = result.Content;
bodyOutput = content.ReadAsStringAsync().Result;
break;
case "POST":
//bodyInput
break;
case "PUT":
break;
case "DELETE":
break;
default:
break;
}
return bodyOutput;
}
}
Thanks
Solution 1:[1]
call this function using await , unlike what your doing in your function. Post :
static async Task<string> Postfunc()
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new object obj());
var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = await response.Content.ReadAsStringAsync();
return result;
}
Solution 2:[2]
Hi your code should look like this:
static async Task Main(string[] args)
{
string baseAddress = ConfigurationManager.AppSettings["baseAddress"];
string path = ConfigurationManager.AppSettings["path"];
string jsonBody = "";
HttpMethod method = HttpMethod.Get;
string result = await CallApi(baseAddress, path, method, jsonBody);
}
public static async Task<string> CallApi(string baseAddress, string path, HttpMethod method, string body)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = null;
switch (method)
{
case HttpMethod.Get:
response = await client.GetAsync(path);
break;
case HttpMethod.Post:
response = await client.PostAsJsonAsync(path, body);
break;
case HttpMethod.Put:
response = await client.PutAsJsonAsync(path, body);
break;
case HttpMethod.Delete:
response = await client.DeleteAsync(path);
break;
default:
throw new NotImplementedException();
}
// Throw an exception if the response code is not successful
response.EnsureSuccessStatusCode();
// Read the response
string bodyOutput = await response.Content.ReadAsStringAsync();
return bodyOutput;
}
}
You can see a more detailed example here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
