c# httpclient - How to add cookies to WebRequest?

2 Answers

Based on your comments, you might consider writing an extension method:

public static bool TryAddCookie(this WebRequest webRequest, Cookie cookie)
    HttpWebRequest httpRequest = webRequest as HttpWebRequest;
    if (httpRequest == null)
        return false;

    if (httpRequest.CookieContainer == null)
        httpRequest.CookieContainer = new CookieContainer();

    return true;

Then you can have code like:

WebRequest webRequest = WebRequest.Create( uri );
webRequest.TryAddCookie(new Cookie("someName","someValue"));
httpwebrequest example

I am trying to unit test some code, and I need to to replace this:

  HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create( uri );
  httpWebRequest.CookieContainer = new CookieContainer();


  WebRequest webRequest = WebRequest.Create( uri );
  webRequest.CookieContainer = new CookieContainer(); 

Basically, how do I get cookies into the request without using a HttpWebRequest?

Try with something like this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/default.html");
request.CookieContainer.Add(new Cookie("ConstoCookie", "Chocolate Flavour"));


c# .net unit-testing