首頁>技術>

RestSharp 是一個開源的 Http 客戶端類庫,非常方便和 RESTful 格式的 Service 進行互動,的是,這個類庫封裝了 request 請求過程中複雜的細節,而且 RestSharp 支援同步和非同步兩種請求模式。

實現 DefaultController

開啟 DefaultController.cs 檔案並用下面的程式碼進行替換。

using Microsoft.AspNetCore.Mvc;using System.Collections.Generic;namespace RESTAPIDemo.Controllers{    [Route("api/[controller]")]    [ApiController]    public class DefaultController : ControllerBase    {        private readonly Dictionary<int, string> authors = new Dictionary<int, string>();        public DefaultController()        {            authors.Add(1, "Joydip Kanjilal");            authors.Add(2, "Steve Smith");            authors.Add(3, "Michele Smith");        }        [HttpGet]        public List<string> Get()        {            List<string> lstAuthors = new List<string>();            foreach (KeyValuePair<int,string> keyValuePair in authors)                lstAuthors.Add(keyValuePair.Value);            return lstAuthors;        }        [HttpGet("{id}", Name = "Get")]        public string Get(int id)        {            return authors[id];        }        [HttpPost]        public void Post([FromBody] string value)        {            authors.Add(4, value);        }        [HttpPut("{id}")]        public void Put(int id, [FromBody] string value)        {            authors[id] = value;        }        [HttpDelete("{id}")]        public void Delete(int id)        {            authors.Remove(id);        }    }}

參考上面的 DefaultController 類,可以發現 Action 方法的名字對應著 Http 動詞的 GET,POST,PUT 和 DELETE,為了簡單起見,我使用了 Dictionary 來存取資料,你可以用 瀏覽器 或者 Postman 或者 Fiddler 進行測試,請注意,這裡為了方便,我在 Post 方法中使用了硬編碼,實際場景中你可以用自己的方式生成唯一ID。

接下來的章節我們將會學習如何使用 RestSharp 去呼叫剛才構建的 API 介面。

安裝 RestSharp

要想使用 RestSharp,你可以使用 Visual Studio 2019 中的 NuGet package manager 視覺化介面進行安裝,或者透過 NuGet package manager console 命令列輸入如下命令:

Install-Package RestSharp
使用 RestSharp 呼叫 ASP.NET Core API

一旦 RestSharp 成功引用到專案之後,就可以使用它了,首先, 你需要建立 RestClient 例項,下面的程式碼展示瞭如何對 RestClient 進行例項化和初始化操作,要注意的是建構函式中的 url 配置的是 基址,言外之意這不是完整的url。

RestClient client = new RestClient("http://localhost:58179/api/");

接下來,你可以傳遞 資源名請求方式 兩個引數來例項化 RestRequest 物件,下面的程式碼展示瞭如何實現。

RestRequest request = new RestRequest("Default", Method.GET);

最後,你可以執行 request 請求,再將返回的結果序列化, 最後用一個合適的物件接收,就像下面程式碼一樣。

IRestResponse<List<string>> response = client.Execute<List<string>>(request);

下面是完整的可供參考的程式碼清單。

using RestSharp;using System;using System.Collections.Generic;namespace RESTSharpClientDemo{    class Program    {        private static RestClient client = new RestClient("http://localhost:58179/api/");        static void Main(string[] args)        {            RestRequest request = new RestRequest("Default",Method.GET);            IRestResponse<List<string>> response = client.Execute<List<string>>(request);            Console.ReadKey();        }    }}

如果想使用 RestSharp 傳送 POST 請求,可以使用如下程式碼。

21
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 如何將日誌記錄到 Windows事件日誌 中