The cookie is not a limited only to Web browsers. Any http-aware client this supports cookie can deal with a cookie sending aSp. NET Web API. The following code example shows a class extended from WebClient. It overrides the virtual method getwebrequest to attach a instance of Cookiecontainer to the request. The Cookiecontainer object instance have to is reused across the requests to let it push cookie in the subsequent requests . For this reason, it is a class-level field and the same instance of the Web client are used to send multiple requests. Here we use a proxy of the address localhost and port 8888, that's Fiddler, to inspect requests and responses.
Public classcookiewebclient:webclient {PrivateCookiecontainer jar =NewCookiecontainer (); protected OverrideWebRequest GetWebRequest (Uri address) {WebRequest request =Base. GetWebRequest (address); HttpWebRequest WebRequest = Request asHttpWebRequest;if(WebRequest! =NULL) Webrequest.cookiecontainer = jar;returnrequest; } } stringURL ="http://localhost:7077/api/employees/12345";
Chapter 4 http anatomy and SeCurity
70
Cookiewebclient client = new Cookiewebclient () {Proxy = new WebProxy ("localhost", 8888)//Fiddler}; Console.WriteLine (client. Downloadstring (URL)); Cookies are created here Console.WriteLine (client. Downloadstring (URL)); In this request, the cookie gets sent the Web API
How to create a cookie using WebClient in C #