.Net 简单封装 Flurl 使用HTTP发送Get和Post 请求
  tmCXeMJfNjuK 2024年03月03日 79 0

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);
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年03月03日 0

暂无评论

推荐阅读
  NPQODODLqddb   2024年05月17日   69   0   0 .NET
  mVIyUuLhKsxa   2024年05月17日   52   0   0 .NET
  XkHDHG7Y62UM   2024年05月17日   45   0   0 .NET
  f18CFixvrKz8   2024年05月18日   85   0   0 .NET
  rBgzkhl6abbw   2024年05月18日   77   0   0 .NET
  MYrYhn3ObP4r   2024年05月17日   41   0   0 .NET
  S34pIcuyyIVd   2024年05月17日   59   0   0 .NET
  gKJ2xtp6I8Y7   2024年05月17日   50   0   0 .NET
  MYrYhn3ObP4r   2024年05月17日   39   0   0 .NET
tmCXeMJfNjuK