2010-11-08 89 views
1

我正在尝试构建一个C#控制台应用程序来测试为各种事情使用Cookie的休息服务。我一直在尝试使用hammock,但它似乎没有管理Cookie。是否有一个处理Cookie的C#休息客户端?

是否有一个C#休息客户端管理Cookie?

+0

你是否试图在测试中自动化测试? Fiddler有一个选项可以发送你可以用于REST的原始HTTP。 – Aliostad 2010-11-08 17:10:24

+0

@Alostad - 我的目标不是为剩下的服务创建一个客户端库,我最终可以挂钩到nunit中运行自动化测试。这也将成为Silverlight客户端的基础。 – 2010-11-08 18:13:44

回答

1

你可以使用HttpWebReqest吗?如果是这样的话,那么这个类就可以使用cookie处理CookieContainer类。

详情请参阅此相关的问题:Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse

+0

我一直在寻找使用HttpWebRequest和HttpWebResponse对象,但他们是一个较低的水平,然后我希望处理。例如,Hammock有一个简单的API来发布数据,看起来我必须构建一些基础结构,以便使用HttpWebReqeust和HttpWebResponse完成此操作。 – 2010-11-08 18:19:15

+0

我最终使用CookieContainer像你所建议的HttpWebRequest。 – 2010-11-10 19:17:26

0

我个人认为Steve Haigh's answer是很容易的,但如果你固执的话,你可以使用一个WebClient和利用HeadersResponseHeaders财产。其余的要求自己变得更简单和更高层次,但是cookie操作变得更加痛苦。

这让我觉得这是一笔糟糕的交易,但我认为这是对史蒂夫建议的另一种可能的选择,您不喜欢这一建议。

如果您想编写一个WebClient包装类来为您完成此操作,您可能会发现Jim's WebClient class有帮助。

1

你可以在吊床上处理饼干。虽然它在代码中看起来不自然,但它起作用。您必须手动将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; 
    } 
} 
2

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

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

一旦你做到了这一点,后续调用Execute/Execute<T>/ExecuteAsync/ExecuteAsync<T>将处理cookie预期。