.NET HttpClient扩展
/// <summary> /// HttpClient扩展类 /// </summary> public static class HttpClientExtensions { /// <summary> /// HttpClient请求封装 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="method"></param> /// <param name="url"></param> /// <param name="sendContent"></param> /// <returns></returns> public static async Task<ResultInfo<TResult>> RequestAsync<T, TResult>(this HttpClient client, HttpMethod method, string url, T sendContent = default(T)) { HttpRequestMessage requestMessage = new HttpRequestMessage(method, url) { Content = method == HttpMethod.Get ? null : new ObjectContent<T>(sendContent, new JsonMediaTypeFormatter()) }; var response = await client.SendAsync(requestMessage); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsAsync<TResult>(); return new ResultInfo<TResult>(true, "请求成功") { Data = content }; } else { var error = await response.Content.ReadAsAsync<HttpError>(); return new ResultInfo<TResult>(false, error.Message); } } }