I'm attempting to build a c# console application to test a rest service that uses cookies for various things. I have been attempting to use hammock but it does not appear to manage cookies.
Is there a c# rest client that m开发者_开发知识库anages cookies?
You can handle cookies on Hammock. Although It does not look natural in code, it works. You have to manually save the cookies on each response, and inyect them on each subsequent request. This is part of the code that I use on a class that consumes a web service. On other methods, instead of calling RestClient.Request(), I call _Request() so it handles the cookies every time I make one request.
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;
}
}
Additionally, RestSharp supports automatic cookie management. It does so internally by using HttpWebRequest
and using CookieContainer
. To support this, you simply need to set the IRestClient.CookieContainer
property when creating your shared IRestClient
:
var client = new RestClient("http://api.server.com/")
{
CookieContainer = new CookieContainer();
};
Once you've done this, subsequent calls to Execute
/Execute<T>
/ExecuteAsync
/ExecuteAsync<T>
will handle cookies as expected.
Can you use the HttpWebReqest? If so, that has cookie handling with the CookieContainer
class.
See this related question for more details: Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse
Personally I think Steve Haigh's answer is much easier, but if you're stubborn enough you can use a WebClient
and make use of the Headers
and ResponseHeaders
property. The rest requests themselves then become much simpler and higher level, but the cookie manipulation becomes more painful.
This strikes me as a poor trade, but I am suggesting it as a possible alternative to Steve's suggestion, which you did not like.
You may find Jim's WebClient class helpful as a starting point, if you want to write a WebClient wrapper class to do this for you.
精彩评论