写在前面
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();
}
}
运行起来:
调用结果