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
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
CodePudding user response:
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;
}
CodePudding user response:
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
