Skip to main content
 首页 » 编程设计

c#之是否有处理 cookie 的 C# rest 客户端

2024年02月24日17mengfanrong

我正在尝试构建一个 c# 控制台应用程序来测试使用 cookie 进行各种操作的休息服务。我一直在尝试使用 hammock但它似乎不管理 cookie。

是否有管理 cookie 的 c# rest 客户端?

请您参考如下方法:

您可以在 Hammock 上处理 cookie。虽然它在代码中看起来不自然,但它确实有效。您必须在每个响应中手动保存 cookie,并在每个后续请求中输入它们。这是我在使用 Web 服务的类上使用的代码的一部分。在其他方法中,我没有调用 RestClient.Request(),而是调用了 _Request(),因此它会在我每次发出一个请求时处理 cookie。

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; 
    } 
}