ASP.NET 服务处理第三方 API 集成通常涉及以下步骤:
选择合适的 HTTP 客户端库:
安装必要的 NuGet 包:
HttpClient
,通常不需要额外的 NuGet 包。RestSharp
,可以通过 NuGet 包管理器安装:Install-Package RestSharp
创建一个服务类来处理 API 调用:
ThirdPartyApiClient
,并在其中封装所有与第三方 API 交互的逻辑。定义 API 端点和请求参数:
实现 API 调用方法:
HttpClient
或 RestSharp
发送 HTTP 请求,并处理响应。以下是一个使用 HttpClient
的示例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class ThirdPartyApiClient
{
private readonly HttpClient _httpClient;
private const string BaseUrl = "https://api.thirdparty.com";
public ThirdPartyApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetDataAsync(string endpoint, string apiKey)
{
var requestUri = new Uri($"{BaseUrl}/{endpoint}");
var requestHeaders = new[]
{
new KeyValuePair<string, string>("Authorization", $"Bearer {apiKey}")
};
var response = await _httpClient.GetAsync(requestUri, headers: requestHeaders);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task PostDataAsync(string endpoint, string apiKey, object data)
{
var requestUri = new Uri($"{BaseUrl}/{endpoint}");
var requestContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
var requestHeaders = new[]
{
new KeyValuePair<string, string>("Authorization", $"Bearer {apiKey}")
};
var response = await _httpClient.PostAsync(requestUri, requestContent, headers: requestHeaders);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
ThirdPartyApiClient
并调用其方法来处理 API 请求。以下是一个简单的 ASP.NET Core 控制器示例,使用 ThirdPartyApiClient
:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ThirdPartyController : ControllerBase
{
private readonly ThirdPartyApiClient _apiClient;
public ThirdPartyController(ThirdPartyApiClient apiClient)
{
_apiClient = apiClient;
}
[HttpGet("data")]
public async Task<IActionResult> GetData()
{
var apiKey = "your-api-key";
var data = await _apiClient.GetDataAsync("endpoint", apiKey);
return Ok(data);
}
[HttpPost("data")]
public async Task<IActionResult> PostData([FromBody] object data)
{
var apiKey = "your-api-key";
var response = await _apiClient.PostDataAsync("endpoint", apiKey, data);
return Ok(response);
}
}
通过以上步骤,你可以在 ASP.NET 应用中有效地集成和处理第三方 API。