当前位置 : 主页 > 网络编程 > c#编程 >

C#使用RestClient调用WebAPI

来源:互联网 收集:自由互联 发布时间:2023-01-31
获取Token /// summary /// 获取Token /// /summary /// returns/returns public static async Taskstring GetToken() { var url = $"http://127.0.0.1/terminal-tenant/sys/login"; var client = new RestClient(url); var request = new RestRequest(Me

获取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#线程的全面解析
下一篇:没有了
网友评论