how to write a post controller action method to call an external api in .Net Core Web API

1.7k Views Asked by At

I am having an end point url, request json, response json and an authentication token for external api and now I need to post the request to this api from my controller action method in .Net Core Web API. I am not able to find any useful reference from the internet to construct this post controller action method in .Net Core Web API.

1

There are 1 best solutions below

0
On

I am having an end point url, request json, response json and an authentication token for external api and now I need to post the request to this api from my controller action method in .Net Core Web API.

You can refer to the following code snippet to make request(s) with posted data from your action method to another external api.

var url = "https://xxx/xx/xx";
var jsondata = System.Text.Json.JsonSerializer.Serialize(${payLoad_here});
var content = new StringContent(jsondata, System.Text.Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Add("Authorization", $"bearer {your_token_here}");

var response = await _httpClient.PostAsync(url, content);

if (response.IsSuccessStatusCode)
{
    var result = await response.Content.ReadAsStringAsync();
    var data = System.Text.Json.JsonSerializer.Deserialize<MyTestModel>(result);
    return Json(data);
}

return Json("Error");

And you need to register IHttpClientFactory and related services in Startup.cs.

services.AddHttpClient();

For more information about "Make HTTP requests using IHttpClientFactory in ASP.NET Core", please check following doc:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#basic-usage