C#使用FluentHttpClient實(shí)現(xiàn)請(qǐng)求WebApi
寫(xiě)在前面
FluentHttpClient 是一個(gè)REST API 異步調(diào)用 HTTP 客戶端,調(diào)用過(guò)程非常便捷,采用流式編程,可以將所有請(qǐng)求所需的參數(shù)一次性發(fā)送,并直接獲取序列化后的結(jié)果。
老規(guī)矩從NuGet上安裝該類庫(kù):
這邊一定要認(rèn)準(zhǔn)是 Pathoschild 這家,千萬(wàn)不要下錯(cuò),因?yàn)橛蓄愃脐P(guān)鍵詞的類庫(kù)。
代碼實(shí)現(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模板項(xiàng)目,運(yùn)行框架是.Net8.0,現(xiàn)在已經(jīng)集成了Swagger,超級(jí)贊的,運(yùn)行起來(lái)可以直接看到這樣的界面。
對(duì)應(yīng)的控制器代碼如下:
[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(); } }
運(yùn)行起來(lái):
調(diào)用結(jié)果
到此這篇關(guān)于C#使用FluentHttpClient實(shí)現(xiàn)請(qǐng)求WebApi的文章就介紹到這了,更多相關(guān)C# FluentHttpClient請(qǐng)求WebApi內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#類繼承中構(gòu)造函數(shù)的執(zhí)行序列示例詳解
這篇文章主要給大家介紹了關(guān)于C#類繼承中構(gòu)造函數(shù)的執(zhí)行序列的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09C# PaddleDetection yolo實(shí)現(xiàn)印章檢測(cè)
這篇文章主要為大家詳細(xì)介紹了C#如何結(jié)合PaddleDetection yolo實(shí)現(xiàn)印章檢測(cè),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11C#實(shí)現(xiàn)的中國(guó)移動(dòng)官網(wǎng)手機(jī)號(hào)碼采集器
這篇文章主要介紹了C#實(shí)現(xiàn)的中國(guó)移動(dòng)官網(wǎng)手機(jī)號(hào)碼采集器,本文先是采集號(hào)碼入庫(kù),同時(shí)給出了篩選各類靚號(hào)的SQL語(yǔ)句,需要的朋友可以參考下2014-10-10C#實(shí)現(xiàn)簡(jiǎn)易計(jì)算器小功能
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)易計(jì)算器小功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01