简体   繁体   中英

ASP.NET Web API post to an external api

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.

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>();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM