简体   繁体   English

ASP.NET Web API 发布到外部 api

[英]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?我想问一下创建的 ASP.NET Web API(用 C# 编写)是否可以发布到外部 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.如果可能,请分享示例代码,该代码可以通过添加标题发布到 url 并接收来自外部 API 的回调。

A simple way to make HTTP-Request out of a .NET-Application is the System.Net.Http.HttpClient ( MSDN ). System.Net.Http.HttpClient ( MSDN ) 是从 .NET 应用程序中发出 HTTP 请求的一种简单方法。 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.本质上,您需要使用HttpClient的实例将HttpRequestMessage发送到端点。

Here is an example to post some jsonData to someEndPointUrl :这是一个将一些jsonDatasomeEndPointUrl的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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