Handling Cookies

Sending and receiving cookies to/from your REST service using WebApiClient is very easy. Take a look at the examples below.

Sending Cookies

To send cookies to the WebApi, all you have to do is to call the AddCookie method:

WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants");

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
{
    client.AddCookie(new Cookie("restaurantId", "1", "/", "localhost"));
    client.AddCookie(new Cookie("dummyCookie1", "dummy value 1", "/", "localhost"));
    client.AddCookie(new Cookie("dummyCookie2", "dummy value 2", "/", "localhost"));

    var rest = await client.GetOneAsync("getUsingCookie");
}

Although it doesn't make any difference when sending cookies, you can use the HttpClientHandler embeded cookie container:

var handler = new HttpClientHandler() { UseCookies = true };

var cc = new CookieContainer();
cc.Add(new Cookie("restaurantId", "1", "/", "localhost"));
cc.Add(new Cookie("dummyCookie1", "dummy value 1", "/", "localhost"));
cc.Add(new Cookie("dummyCookie2", "dummy value 2", "/", "localhost"));
handler.CookieContainer = cc;

WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants");

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options, handler))
{
    var rest = await client.GetOneAsync("getUsingCookie");
}

To access the cookie collection in your REST service method, you can code something like this:

var cookie = Request.Headers.GetCookies();

int id = Convert.ToInt32(cookie["restaurantId"].Value);

Receiving Cookies

To get cookies the WebApi has sent to the client, you'll always use the HttpClientHandler embeded cookie container:

WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants");

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
{
    var rest = await client.GetOneAsync(1);

	//Returns a CookieCollection
	var col = client.Handler.CookieContainer.GetCookies(new Uri(options.BaseAddress));

	Assert.AreEqual("12345", col["session-id"].Value);
}

To send a cookie collection in your REST service method, you can code something like this:

var response = Request.CreateResponse(HttpStatusCode.OK);

response.Headers.AddCookies(new CookieHeaderValue[] { 
				new CookieHeaderValue("session-id", "12345") { 
							Expires = DateTimeOffset.Now.AddDays(1), 
							Domain = Request.RequestUri.Host, 
							Path = "/" 
				}
		});