C# 使用FluentHttpClient请求WebApi

写在前面

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

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

C# 使用FluentHttpClient请求WebApi_第1张图片

这边一定要认准是 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>();
        //var items = await client.PostAsync("WeatherForecast").As>();
        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,超级赞的,运行起来可以直接看到这样的界面。

C# 使用FluentHttpClient请求WebApi_第2张图片

对应的控制器代码如下:

    [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 _logger;

        public WeatherForecastController(ILogger logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        [HttpPost(Name = "GetWeatherForecast")]
        public IEnumerable 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_第3张图片 

调用结果

C# 使用FluentHttpClient请求WebApi_第4张图片

 

你可能感兴趣的:(C#,c#,windows,开发语言)