REST 是由 Representational State Transfer 这三个单词前缀合成,这种架构风格在前几年特别流行,Restful API 的行为规范可以参考: https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design ,通常 RESTful API 返回的格式为常见的 PlianText, JSON , XML 格式。
这篇文章将会讨论如何使用 RestSharp 去请求 Asp.NET Core 服务。
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 接口。
Install-Package RestSharp使用 RestSharp 调用 ASP.NET Core API
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(); } } }
RestRequest request = new RestRequest("Default", Method.POST); request.AddJsonBody("Robert Michael"); var response = client.Execute(request);RestSharp 可以跨多个 .NET 平台使用,比如说:Momo,Xarmain,Blazer 等等,这也是它为什么非常流行的原因,而且 RestSharp 支持通过泛型方式获取结果,这个特性特别 🐂👃,想了解更多 RestSharp 知识,可参考 Github:https://github.com/restsharp/RestSharp