C〓〓〓〓Rest Sharp応用


C〓〓〓〓Rest Sharp応用
ブログを開設するには、自分の学んだことを記録して、自分で調べて、漏れを補うために、自分で頑張りたいです。
本題はRestt Sharpの使用についてです。
  • .NuGetをダウンロードして直接検索すればいいです。最新バージョンのRest Sharpは.net frame ebook 4.5.2と以上のサポートが必要です。
  • Jsonプログレッシブツール:Newtonift.Json、直接NuGetから
  • をダウンロードします。
  • 公式サイトの説明:
  • 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(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(request, response => {
        Console.WriteLine(response.Data.Name);
    });
    
    // abort the request on demand
    asyncHandle.Abort();
    
  • 工具類を書く
  • public class RestSharpApiUtil
        {
            #region       
            /// 
            ///   Client,Request,   Http  
            /// 
            ///      
            ///    
            ///     
            ///     
            /// Get/Put/Delete/Post   
            /// post   
            /// 
            public static ResponseMessage RestAction(string baseUrl, string relativeUrl, Method method=Method.GET,List lstParam=null)
            {
                var client = new RestClient(baseUrl);
                return RestMethod(client, InstallRequest(relativeUrl,method,lstParam));
            }
    
            /// 
            ///         
            /// 
            /// 
            /// 
            /// 
            /// 
            /// 
            public static void RestActionNoResponseAsync(string baseUrl, string relativeUrl, Method method = Method.GET, List lstParam = null)
            {
                var client = new RestClient(baseUrl);
                RestMethodWithOutReturnAsync(client, InstallRequest(relativeUrl, method, lstParam));
            }
    
            #endregion
    
            #region     ,      
            /// 
            /// Http  
            /// 
            /// 
            /// 
            /// 
            /// 
            static ResponseMessage RestMethod(RestClient client, RestRequest request)
            {
                RestResponse restResponse = (RestResponse)client.Execute(request);
                try
                {
                    return restResponse == null ? new ResponseMessage() :
                        string.IsNullOrWhiteSpace(restResponse.Content) ? new ResponseMessage() :
                        JsonConvert.DeserializeObject>(restResponse.Content);
                }
                catch (Exception ex)
                {
                    return new ResponseMessage() { success = false };
                }
            }
    
            /// 
            ///         
            /// 
            /// 
            /// 
            static void RestMethodWithOutReturnAsync(RestClient client, RestRequest request)
            {
                RestResponse restResponse;
                var asyncHandle = client.ExecuteAsync(request, response =>
                {
                    restResponse = (RestResponse)response;
                });
                asyncHandle.Abort();
            }
    
            /// 
            ///   Request
            /// 
            /// 
            /// 
            /// 
            /// 
            static RestRequest InstallRequest(string relativeUrl, Method method = Method.GET, List 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
    
        }
    
    このうち、2つのクラスを使用します。Response Message:値エンティティに戻り、自分の業務に応じてRetsParam:パラメータエンティティとパラメータタイプを組み立てることができます。