关于.net:如何使用-RestSharp-调用-WebAPI-接口

11次阅读

共计 2761 个字符,预计需要花费 7 分钟才能阅读完成。

REST 是由 Representational State Transfer 这三个单词前缀合成,这种架构格调在前几年特地风行,Restful API 的行为规范能够参考: https://docs.microsoft.com/en…,通常 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/…

译文链接:https://www.infoworld.com/art…

更多高质量干货:参见我的 GitHub: csharptranslate

正文完
 0