C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# FluentHttpClient请求WebApi

C#使用FluentHttpClient实现请求WebApi

作者:rjcql

FluentHttpClient 是一个REST API 异步调用 HTTP 客户端,调用过程非常便捷,下面我们就来学习一下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();
        }
    }

运行起来:

调用结果

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

您可能感兴趣的文章:
阅读全文