C#使用RestClient呼叫Web API
阿新 • • 發佈:2022-03-07
- 獲取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; }
本文來自部落格園,作者:農碼一生,轉載請註明原文連結:https://www.cnblogs.com/wml-it/p/15976136.html
技術的發展日新月異,隨著時間推移,無法保證本部落格所有內容的正確性。如有誤導,請大家見諒,歡迎評論區指正!
個人開原始碼連結,歡迎點亮:
GitHub:https://github.com/ITMingliang
Gitee:https://gitee.com/mingliang_it
GitLab:https://gitlab.com/ITMingliang
進開發學習交流群: