我正在尝试使c#客户端与Rest Api通信。具有通用方法的单例客户端,用于将获取/发布请求发送到服务器。只是,我不确定这是否是正确的方法,并想获得一些反馈:
internal class ApiClient : HttpClient
{
private static readonly Lazy<ApiClient> lazyApiClient =
new Lazy<ApiClient>(() => new ApiClient());
private static readonly ApiClient instance = new ApiClient();
static ApiClient() { }
private ApiClient() : base()
{
}
public static ApiClient Instance
{ get { return lazyApiClient.Value; } }
private async Task<T> SendAsyncRequest<T>(HttpRequestMessage httpRequestMessage) where T : IApiResponse
{
using (httpRequestMessage)
{
HttpResponseMessage response = await SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead)
.ConfigureAwait(false);
{
response.EnsureSuccessStatusCode();
string responeString = response.Content.ReadAsStringAsync().Result;
return await response.Content.ReadAsAsync<T>();
}
}
}
public async Task<T> Get<T>(string uriString) where T : IApiResponse
{
if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(uriString) };
return await SendAsyncRequest<T>(httpRequestMessage);
}
public async Task<T> Post<T>(string jsonContent, string uriString) where T : IApiResponse
{
if (string.IsNullOrEmpty(jsonContent)) throw new ArgumentNullException("missing json content");
if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
StringContent stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Content = stringContent, Method = HttpMethod.Post, RequestUri = new Uri(uriString) };
return await SendAsyncRequest<T>(httpRequestMessage);
}
}