3

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.

2 Answers 2

3

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>();
Sign up to request clarification or add additional context in comments.

Comments

0

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:

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 ?
    }

2 Comments

HttpClient should only be created once and not be disposed
@MrCodingB noted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.