这篇文章介绍了C#使用RestClient调用WebAPI的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
获取Token
/// <summary>
/// 获取Token
/// </summary>
/// <returns></returns>
public static async Task<string> GetToken()
{
var url = $"http://127.0.0.1/terminal-tenant/sys/login";
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
var body = new { username = "xxx", password = "xxx" };
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(body), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var responseContent = response.Content;
return responseContent;
}
保存数据
/// <summary>
/// 保存数据
/// </summary>
/// <returns></returns>
public async Task<string> Save(Model model, string token)
{
var url = $"http://127.0.0.1/terminal-tenant/app/visitor/save";
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("token", token);
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(model), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var responseContent = response.Content;
return responseContent;
}
上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <param name="bt"></param>
/// <param name="token"></param>
/// <returns></returns>
public async Task<string> Upload(byte[] bt, string token)
{
var url = $"http://127.0.0.1/terminal-tenant/tenant/common/upload";
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("token", token);
request.AddFile("file", bt, "multipart/form-data");
IRestResponse response = client.Execute(request);
var responseContent = response.Content;
return responseContent;
}
到此这篇关于C#使用RestClient调用Web API的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:C#使用RestClient调用Web API
基础教程推荐
猜你喜欢
- C# windows语音识别与朗读实例 2023-04-27
- unity实现动态排行榜 2023-04-27
- C#类和结构详解 2023-05-30
- C# 调用WebService的方法 2023-03-09
- C#控制台实现飞行棋小游戏 2023-04-22
- C# List实现行转列的通用方案 2022-11-02
- winform把Office转成PDF文件 2023-06-14
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- ZooKeeper的安装及部署教程 2023-01-22
- 一个读写csv文件的C#类 2022-11-06