.net6 Json API POST请求 方法封装
时间: 2024-04-15 22:24:21 浏览: 19
在 .NET 6 中,可以使用 System.Net.Http 命名空间中的 HttpClient 类来发送 POST 请求。下面是一个简单的封装方法示例:
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace YourNamespace
{
public static class ApiClient
{
private static readonly HttpClient _httpClient = new HttpClient();
public static async Task<TResponse> PostAsync<TRequest, TResponse>(string url, TRequest request)
{
var requestJson = JsonSerializer.Serialize(request);
var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"POST request failed with status code {response.StatusCode}");
}
var responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TResponse>(responseJson);
}
}
}
```
使用时,你可以调用 `PostAsync` 方法,并传递请求的 URL 和请求对象。以下是一个示例:
```csharp
var request = new YourRequestObject
{
// 设置请求对象属性
};
var response = await ApiClient.PostAsync<YourRequestObject, YourResponseObject>("https://api.example.com/endpoint", request);
// 处理响应对象
```
请注意,上述示例假设请求和响应对象都是可序列化为 JSON 的类型,并且使用了默认的 JSON 序列化设置。你可能需要根据自己的需求进行适当的修改和调整。