C#使用FluentHttpClient實現請求WebApi
更新時間:2023年12月19日 08:47:38 作者:rjcql
FluentHttpClient 是一個REST API 異步調用 HTTP 客戶端,調用過程非常便捷,下面我們就來學習一下C#如何使用FluentHttpClient實現請求WebApi吧
寫在前面
FluentHttpClient 是一個REST API 異步調用 HTTP 客戶端,調用過程非常便捷,采用流式編程,可以將所有請求所需的參數一次性發(fā)送,并直接獲取序列化后的結果。
老規(guī)矩從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內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!