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。