Home > Enterprise >  ASP.NET Web API post to an external api
ASP.NET Web API post to an external api

Time:06-04

I would like to ask if it is possible for a created ASP.NET Web API (written in C#) to post to an external API?

If it is possible, please share sample code that can post to an url with adding headers and receive a callback from the external API.

CodePudding user response:

A simple way to make HTTP-Request out of a .NET-Application is the System.Net.Http.HttpClient (MSDN). An example usage would look something like this:

// Should be a static readonly field/property, wich is only instanciated once
var client = new HttpClient();

var requestData = new Dictionary<string, string>
{  
    { "field1", "Some data of the field" },
    { "field2", "Even more data" }
};

var request = new HttpRequestMessage() {
    RequestUri = new Uri("https://domain.top/route"),
    Method = HttpMethod.Post,
    Content = new FormUrlEncodedContent(requestData)
};

request.Headers // Add or modify headers

var response = await client.SendAsync(request);

// To read the response as string
var responseString = await response.Content.ReadAsStringAsync();

// To read the response as json
var responseJson = await response.Content.ReadAsAsync<ResponseObject>();

CodePudding user response:

Have you tried anything ?

Essentially you need use an instance of HttpClient to send an HttpRequestMessage to an endpoint, Here is an example to post some jsonData to someEndPointUrl

using(var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, someEndPointUrl);
        request.Headers.Accept.Clear();
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        var response = await client.SendAsync(request, CancellationToken.None);

        var str = await response.Content.ReadAsStringAsync();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            //handle your response
        }else{
           //or failed response ?
        {
    }
  • Related