代码之家  ›  专栏  ›  技术社区  ›  Aaron Carlson

有处理cookies的C#rest客户机吗?

  •  1
  • Aaron Carlson  · 技术社区  · 15 年前

    我正试图构建一个c#控制台应用程序来测试一个rest服务,该服务使用cookies来处理各种事情。我一直试图利用 hammock

    有管理cookies的c#rest客户机吗?

    4 回复  |  直到 15 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    你能用httpwebrequest吗?如果是的话,那就用 CookieContainer 上课。

    Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse

        2
  •  2
  •   Pete    14 年前

    另外, RestSharp 支持自动cookie管理。它在内部使用 HttpWebRequest CookieContainer . 为了支持这一点,您只需要设置 IRestClient.CookieContainer 创建共享时的属性 IRestClient

    var client = new RestClient("http://api.server.com/")
    {
        CookieContainer = new CookieContainer();
    };
    

    完成此操作后,随后将调用 Execute / Execute<T> ExecuteAsync / ExecuteAsync<T> 将按预期处理cookies。

        3
  •  1
  •   Diego    15 年前

    using System.Collections.Specialized;
    using Hammock;
    using System.Net;
    
    static class Server {
        private static RestClient Client;
        private static NameValueCollection Cookies;
        private static string ServerUrl = "http://www.yourtarget.com/api"; 
    
        private static RestResponse _Request(RestRequest request) {
            //If there was cookies on our accumulator...
            if (Cookies != null)
            {
                // inyect them on the request
                foreach (string Key in Cookies.AllKeys)
                request.AddCookie(new Uri(ServerUrl), Key, Cookies[Key]);
            }
    
            // make the request
            RestResponse response = Client.Request(request);
    
            // if the Set-Cookie header is set, we have to save the cookies from the server.
            string[] SetCookie = response.Headers.GetValues("Set-Cookie");
    
            //check if the set cookie header has something
            if (SetCookie.Length > 0)
            {
                // if it has, save them for future requests
                Cookies = response.Cookies;
            }
    
            // return the response to extract content
            return response;
        }
    }
    
        4
  •  0
  •   Community Mohan Dere    9 年前

    我个人认为 Steve Haigh's answer 更容易,但如果你足够固执,你可以用 WebClient 利用 Headers ResponseHeaders

    我觉得这是一个糟糕的交易,但我建议它作为史蒂夫建议的一个可能的替代品,你不喜欢。

    你可能会发现 Jim's WebClient class