当前位置: 首页 > news >正文

C# 使用FluentHttpClient请求WebApi

写在前面

FluentHttpClient 是一个REST API 异步调用 HTTP 客户端,调用过程非常便捷,采用流式编程,可以将所有请求所需的参数一次性发送,并直接获取序列化后的结果。

老规矩从NuGet上安装该类库:

这边一定要认准是 Pathoschild 这家,千万不要下错,因为有类似关键词的类库。

代码实现


using Pathoschild.Http.Client;
using System;class Program
{static async Task Main(string[] args){var client = new FluentClient("http://localhost:5000/");var items = await client.GetAsync("WeatherForecast").WithHeader("User-Agent", "Tester").WithArguments(new { page = 1, page_size = 10, target = "Day" }).As<List<WeatherForecast>>();//var items = await client.PostAsync("WeatherForecast").As<List<WeatherForecast>>();foreach (var item in items){await Console.Out.WriteLineAsync($"Date: {item.Date.ToShortDateString()}, Summary: {item.Summary}");}Console.ReadLine();}public class WeatherForecast{public DateOnly Date { get; set; }public int TemperatureC { get; set; }public int TemperatureF { get; set; }public string? Summary { get; set; }}
}

WebApi这边直接使用了官方的.NetCore WebApi模板项目,运行框架是.Net8.0,现在已经集成了Swagger,超级赞的,运行起来可以直接看到这样的界面。

对应的控制器代码如下:

    [ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase{private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;public WeatherForecastController(ILogger<WeatherForecastController> logger){_logger = logger;}[HttpGet(Name = "GetWeatherForecast")][HttpPost(Name = "GetWeatherForecast")]public IEnumerable<WeatherForecast> Get(){return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),TemperatureC = Random.Shared.Next(-20, 55),Summary = Summaries[Random.Shared.Next(Summaries.Length)]}).ToArray();}}

运行起来:

 

调用结果

 

http://www.lryc.cn/news/262790.html

相关文章:

  • AXure交互及案列
  • 美颜SDK技术对比,深入了解视频美颜SDK的工作机制
  • OkHttp ,使用 HttpUrl.Builder 来添加查询参数并添加到请求对象
  • 图片速览 PoseGPT:基于量化的 3D 人体运动生成和预测(VQVAE)
  • Java对象结构
  • 基于redis的分布式锁实现方案
  • 基于JAVA+SpringBoot的线上智能问诊就医平台
  • adb: error: cannot create file/directory ‘d:/1.png‘: No such file or directory
  • Pelee: A Real-Time Object Detection System on Mobile Devices(CVPR 2019)
  • 分布式理论 | RPC | Spring Boot 整合 Dubbo + ZooKeeper
  • 局域网其他pc如何访问宿主机虚拟机IP?
  • U8 语法制导翻译技术
  • 剑指offer A + B
  • gitlab(gitlab-ce)下载,离线安装
  • Jmeter接口测试断言
  • Temu、Shein、OZON测评自养号,IP和指纹浏览器的优缺点分析
  • 亚信科技AntDB数据库——深入了解AntDB-M元数据锁的相关概念
  • yolov5 deepsort-船舶目标检测+目标跟踪+单目测距+速度测量
  • Wireshark与其他工具的整合
  • DDD架构实践
  • Bert-vits2-v2.2新版本本地训练推理整合包(原神八重神子英文模型miko)
  • 认识缓存,一文读懂Cookie,Session缓存机制。
  • 关于react native项目中使用react-native-wechat-lib@3.0.4
  • 【LeetCode刷题笔记(8-1)】【Python】【接雨水】【动态规划】【困难】
  • pycharm通过ssh连接远程服务器的docker容器进行运行和调试代码
  • Chrome2023新版收藏栏UI改回旧版
  • WebSocket与JavaScript:实现实时获取位置
  • 一种解决Qt5发布release文件引发的无法定位程序输入点错误的方法
  • UE4/UE5 日志插件(基于spdlog)
  • 微信小程序ios中非cover组件点击重复触发地图tap事件