• 如何使用RestSharp调用WebAPI
  • 发布于 2个月前
  • 406 热度
    0 评论
  • 心已凉
  • 8 粉丝 34 篇博客
  •   

REST 是由 Representational State Transfer 这三个单词前缀合成,这种架构风格在前几年特别流行,Restful API 的行为规范可以参考: https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design  ,通常 RESTful API 返回的格式为常见的 PlianText, JSON , XML 格式。


RestSharp 是一个开源的 Http 客户端类库,非常方便和 RESTful 格式的 Service 进行交互,牛逼的是,这个类库封装了 request 请求过程中复杂的细节,而且 RestSharp 支持同步和异步两种请求模式。

这篇文章将会讨论如何使用 RestSharp 去请求 Asp.NET Core 服务。


实现 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 请求,可以使用如下代码。
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
用户评论