C#使用FluentHttpClient實現(xiàn)請求WebApi
寫在前面
FluentHttpClient 是一個REST API 異步調用 HTTP 客戶端,調用過程非常便捷,采用流式編程,可以將所有請求所需的參數(shù)一次性發(fā)送,并直接獲取序列化后的結果。
老規(guī)矩從NuGet上安裝該類庫:
這邊一定要認準是 Pathoschild 這家,千萬不要下錯,因為有類似關鍵詞的類庫。
代碼實現(xiàn)
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,現(xiàn)在已經(jīng)集成了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實現(xiàn)請求WebApi的文章就介紹到這了,更多相關C# FluentHttpClient請求WebApi內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# PaddleDetection yolo實現(xiàn)印章檢測
這篇文章主要為大家詳細介紹了C#如何結合PaddleDetection yolo實現(xiàn)印章檢測,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-11-11C#實現(xiàn)的中國移動官網(wǎng)手機號碼采集器
這篇文章主要介紹了C#實現(xiàn)的中國移動官網(wǎng)手機號碼采集器,本文先是采集號碼入庫,同時給出了篩選各類靚號的SQL語句,需要的朋友可以參考下2014-10-10