翼度科技»论坛 编程开发 .net 查看内容

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

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
NuGet下载Flurl
FlurlHttpClient类
  1. public class FlurlHttpClient
  2. {
  3.     private readonly FlurlClient client;
  4.     public FlurlHttpClient(FlurlClient client)
  5.     {
  6.         this.client = client;
  7.     }
  8.     public async Task<T> GetAsync<T>(string url) where T : class
  9.     {
  10.         try
  11.         {
  12.             return await client.Request(url).GetJsonAsync<T>();
  13.         }
  14.         catch (FlurlHttpException ex)
  15.         {
  16.             string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式
  17.             IFlurlResponse? response = ex.Call.Response;
  18.             int? statusCode = response is null ? null : response.StatusCode;//服务器状态码
  19.             string errorMsg = $"服务器状态码:{statusCode};Url:{ex.Call.Request.Url};请求方式:{method},入参:无;message:{ex.Message}";
  20.             throw new Exception(errorMsg);
  21.         }
  22.     }
  23.    
  24.     /// <summary>
  25.     /// Get请求
  26.     /// </summary>
  27.     /// <typeparam name="T"></typeparam>
  28.     /// <param name="url">url</param>
  29.     /// <param name="values">参数以对象的形式传入</param>
  30.     /// <returns></returns>
  31.     /// <exception cref="Exception"></exception>
  32.     public async Task<T> GetAsync<T>(string url, object values)
  33.     {
  34.         try
  35.         {
  36.             return await client.Request(url).SetQueryParams(values).GetJsonAsync<T>();
  37.         }
  38.         catch (FlurlHttpException ex)
  39.         {
  40.             string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式
  41.             IFlurlResponse? response = ex.Call.Response;
  42.             string? statusCode = response is null ? null : response.StatusCode.ToString();//服务器状态码
  43.             string errorMsg = $"服务器状态码:{statusCode ?? "无"};Url:{ex.Call.Request.Url};请求方式:{method};入参:{values};message:{ex.Message}";
  44.             throw new Exception(errorMsg);
  45.         }
  46.     }
  47.     /// <summary>
  48.     /// Post请求
  49.     /// </summary>
  50.     /// <typeparam name="T"></typeparam>
  51.     /// <param name="url">url</param>
  52.     /// <param name="values">参数以对象的形式传入</param>
  53.     /// <returns></returns>
  54.     /// <exception cref="Exception"></exception>
  55.     public async Task<T> PostAsync<T>(string url,object values)
  56.     {
  57.         try
  58.         {
  59.             //.ReceiveJson<T>()方法来指定响应的JSON数据会被反序列化为类型T
  60.             return await client.Request(url).PostJsonAsync(values).ReceiveJson<T>();
  61.         }
  62.         catch (FlurlHttpException ex)
  63.         {
  64.             string method = ex.Call.HttpRequestMessage.Method.Method; // 获取请求方式
  65.             IFlurlResponse? response = ex.Call.Response;
  66.             int? statusCode = response is null ? null : response.StatusCode;//服务器状态码
  67.             string errorMsg = $"服务器状态码:{statusCode};Url:{ex.Call.Request.Url};请求方式:{method};入参:{values};message:{ex.Message}";
  68.             throw new Exception(errorMsg);
  69.         }
  70.     }
  71. }
复制代码
注入FlurlHttpClient类
  1. /// <summary>
  2. /// 初始化flurlhttpclient
  3. /// </summary>
  4. /// <param name="builder"></param>
  5. public static void InitFlurlHttpClient(this WebApplicationBuilder builder)
  6. {
  7.     var baseUrl = builder.Configuration["wmsBaseUrl"];
  8.     if (string.IsNullOrEmpty(baseUrl)) throw new Exception("baseUrl未配置");
  9.     //WithHeader添加请求头
  10.     builder.Services.AddScoped(provider => new FlurlClient(baseUrl).WithHeader("test","111"));
  11.     builder.Services.AddScoped(provider => {
  12.         var flurlClient = provider.GetService<FlurlClient>(); // 从依赖注入容器中获取 FlurlClient 类型
  13.         if (flurlClient is null) throw new Exception("系统错误flurlClient类还未注入");
  14.         return new FlurlHttpClient(flurlClient);
  15.     });
  16. }
复制代码
使用
  1. [HttpGet]
  2. public async Task<ActionResult<ApiResponse>> Get()
  3. {
  4.     var resAsync = httpClient.GetAsync<object>("TakeNumber/GetNumber", new { boxNumber = "123456" });
  5.     return this.Success(resAsync);
  6. }
  7. [HttpPost]
  8. public async Task<ActionResult<ApiResponse>> Post()
  9. {
  10.     var resAsync = httpClient.PostAsync<object>("TakeNumber/GetNumber", new { boxNumber = "123456" });
  11.     return this.Success(resAsync);
  12. }
复制代码
来源:https://www.cnblogs.com/cyfj/p/18049436
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具