当前位置: 首页 > 工具软件 > RestSharp > 使用案例 >

C# RestSharp应用

贺刚毅
2023-12-01

C# RestSharp应用

开通博客是想将自己所学的东西记录下来,以便自己查缺补漏,希望自己能坚持下去

正题关于RestSharp的使用

  1. 下载
    NuGet直接搜索即可,最新版本RestSharp需要.net framework 4.5.2及以上支持
  2. Json序列化工具:Newtonsoft.Json,直接由NuGet下载
  3. 官网说明:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("resource/{id}");
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

// add parameters for all properties on an object
request.AddJsonObject(@object);

// or just whitelisted properties
request.AddObject(object, "PersonId", "Name", ...);

// easily add HTTP Headers
request.AddHeader("header", "value");

// add files to upload (works with compatible verbs)
request.AddFile("file", path);

// execute the request
var response = client.Post(request);
var content = response.Content; // raw content as string

// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;

// or download and save file to disk
client.DownloadData(request).SaveAs(path);

// easy async support
await client.ExecuteAsync(request);

// async with deserialization
var asyncHandle = client.PostAsync<Person>(request, response => {
    Console.WriteLine(response.Data.Name);
});

// abort the request on demand
asyncHandle.Abort();
  1. 写一个工具类
public class RestSharpApiUtil
    {
        #region 暴露执行方法
        /// <summary>
        /// 组装Client,Request,并执行Http请求
        /// </summary>
        /// <typeparam name="T">返回值类型</typeparam>
        /// <param name="baseUrl">基地址</param>
        /// <param name="relativeUrl">相对地址</param>
        /// <param name="method">请求类型</param>
        /// <param name="lstParam">Get/Put/Delete/Post等参数</param>
        /// <param name="obj">post请求体</param>
        /// <returns></returns>
        public static ResponseMessage<T> RestAction<T>(string baseUrl, string relativeUrl, Method method=Method.GET,List<RestParam> lstParam=null)
        {
            var client = new RestClient(baseUrl);
            return RestMethod<T>(client, InstallRequest(relativeUrl,method,lstParam));
        }

        /// <summary>
        /// 异步请求无返回值
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="relativeUrl"></param>
        /// <param name="method"></param>
        /// <param name="lstParam"></param>
        /// <param name="obj"></param>
        public static void RestActionNoResponseAsync(string baseUrl, string relativeUrl, Method method = Method.GET, List<RestParam> lstParam = null)
        {
            var client = new RestClient(baseUrl);
            RestMethodWithOutReturnAsync(client, InstallRequest(relativeUrl, method, lstParam));
        }

        #endregion

        #region 底层调用,并不暴露方法
        /// <summary>
        /// Http请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="client"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        static ResponseMessage<T> RestMethod<T>(RestClient client, RestRequest request)
        {
            RestResponse restResponse = (RestResponse)client.Execute(request);
            try
            {
                return restResponse == null ? new ResponseMessage<T>() :
                    string.IsNullOrWhiteSpace(restResponse.Content) ? new ResponseMessage<T>() :
                    JsonConvert.DeserializeObject<ResponseMessage<T>>(restResponse.Content);
            }
            catch (Exception ex)
            {
                return new ResponseMessage<T>() { success = false };
            }
        }

        /// <summary>
        /// 无返回值异步调用
        /// </summary>
        /// <param name="client"></param>
        /// <param name="request"></param>
        static void RestMethodWithOutReturnAsync(RestClient client, RestRequest request)
        {
            RestResponse restResponse;
            var asyncHandle = client.ExecuteAsync(request, response =>
            {
                restResponse = (RestResponse)response;
            });
            asyncHandle.Abort();
        }

        /// <summary>
        /// 组装Request
        /// </summary>
        /// <param name="relativeUrl"></param>
        /// <param name="method"></param>
        /// <param name="lstParam"></param>
        /// <returns></returns>
        static RestRequest InstallRequest(string relativeUrl, Method method = Method.GET, List<RestParam> lstParam = null)
        {
            var request = new RestRequest(relativeUrl, method);
            if (lstParam != null)
            {
                foreach (RestParam p in lstParam)
                {
                    switch (p.ParamType)
                    {
                        case EmParType.UrlSegment:
                            request.AddUrlSegment(p.Key, p.Value);
                            break;
                        case EmParType.Param:
                            request.AddParameter(p.Key, p.Value);
                            break;
                        case EmParType.Body:
                            request.AddJsonBody(p.Value);
                            break;
                        default:
                            break;
                    }
                }
            }
            return request;
        }
        #endregion

    }

其中用到两个类:ResponseMessage:返回值实体,根据自己的业务组装即可
RestParam:参数实体以及参数类型

 类似资料: