GPT4.0+Midjourney绘画+国内大模型 会员永久免费使用!
【 如果你想靠AI翻身,你先需要一个靠谱的工具! 】
写在前面
FluentHttpClient 是一个REST API 异步调用 HTTP 客户端,调用过程非常便捷,采用流式编程,可以将所有请求所需的参数一次性发送,并直接获取序列化后的结果。
老规矩从NuGet上安装该类库:

这边一定要认准是 Pathoschild 这家,千万不要下错,因为有类似关键词的类库。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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,超级赞的,运行起来可以直接看到这样的界面。

对应的控制器代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | [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(); }} |
运行起来:

调用结果

到此这篇关于C#使用FluentHttpClient实现请求WebApi的文章就介绍到这了,更多相关C# FluentHttpClient请求WebApi内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
.png)
.png)
最新评论