.Net 简单封装 Flurl 使用HTTP发送Get和Post 请求

  • .Net 简单封装 Flurl 使用HTTP发送Get和Post 请求已关闭评论
  • 108 次浏览
  • A+
所属分类:.NET技术
摘要

NuGet下载Flurl
FlurlHttpClient类注入FlurlHttpClient类使用

NuGet下载Flurl
FlurlHttpClient类

public class FlurlHttpClient {     private readonly FlurlClient client;      public FlurlHttpClient(FlurlClient client)     {         this.client = client;     }      public async Task<T> GetAsync<T>(string url) where T : class     {         try         {             return await client.Request(url).GetJsonAsync<T>();         }         catch (FlurlHttpException ex)         {             string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式             IFlurlResponse? response = ex.Call.Response;             int? statusCode = response is null ? null : response.StatusCode;//服务器状态码             string errorMsg = $"服务器状态码:{statusCode};Url:{ex.Call.Request.Url};请求方式:{method},入参:无;message:{ex.Message}";             throw new Exception(errorMsg);         }     }         /// <summary>     /// Get请求     /// </summary>     /// <typeparam name="T"></typeparam>     /// <param name="url">url</param>     /// <param name="values">参数以对象的形式传入</param>     /// <returns></returns>     /// <exception cref="Exception"></exception>     public async Task<T> GetAsync<T>(string url, object values)     {         try         {             return await client.Request(url).SetQueryParams(values).GetJsonAsync<T>();         }         catch (FlurlHttpException ex)         {             string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式             IFlurlResponse? response = ex.Call.Response;             string? statusCode = response is null ? null : response.StatusCode.ToString();//服务器状态码             string errorMsg = $"服务器状态码:{statusCode ?? "无"};Url:{ex.Call.Request.Url};请求方式:{method};入参:{values};message:{ex.Message}";             throw new Exception(errorMsg);         }     }       /// <summary>     /// Post请求     /// </summary>     /// <typeparam name="T"></typeparam>     /// <param name="url">url</param>     /// <param name="values">参数以对象的形式传入</param>     /// <returns></returns>     /// <exception cref="Exception"></exception>     public async Task<T> PostAsync<T>(string url,object values)     {         try         {             //.ReceiveJson<T>()方法来指定响应的JSON数据会被反序列化为类型T             return await client.Request(url).PostJsonAsync(values).ReceiveJson<T>();         }         catch (FlurlHttpException ex)         {             string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式             IFlurlResponse? response = ex.Call.Response;             int? statusCode = response is null ? null : response.StatusCode;//服务器状态码             string errorMsg = $"服务器状态码:{statusCode};Url:{ex.Call.Request.Url};请求方式:{method};入参:{values};message:{ex.Message}";             throw new Exception(errorMsg);         }      } } 

注入FlurlHttpClient类

/// <summary> /// 初始化flurlhttpclient /// </summary> /// <param name="builder"></param> public static void InitFlurlHttpClient(this WebApplicationBuilder builder) {     var baseUrl = builder.Configuration["wmsBaseUrl"];     if (string.IsNullOrEmpty(baseUrl)) throw new Exception("baseUrl未配置");      //WithHeader添加请求头     builder.Services.AddScoped(provider => new FlurlClient(baseUrl).WithHeader("test","111"));      builder.Services.AddScoped(provider => {         var flurlClient = provider.GetService<FlurlClient>(); // 从依赖注入容器中获取 FlurlClient 类型         if (flurlClient is null) throw new Exception("系统错误flurlClient类还未注入");         return new FlurlHttpClient(flurlClient);     }); } 

使用

[HttpGet] public async Task<ActionResult<ApiResponse>> Get() {     var resAsync = httpClient.GetAsync<object>("TakeNumber/GetNumber", new { boxNumber = "123456" });     return this.Success(resAsync); } [HttpPost] public async Task<ActionResult<ApiResponse>> Post() {     var resAsync = httpClient.PostAsync<object>("TakeNumber/GetNumber", new { boxNumber = "123456" });     return this.Success(resAsync); }