Cookies are part of the http protocol for websites, they are not available from your windows forms app as the Request\Response objects are provided by the asp.net framework which allows your code to run inside the context of a web request. Your form is just an EXE running on the desktop.
Here is an example of how you can persists cookies yourself using WebClient. This code will allow the target site to know we are a return vististor, and any cookie-based authentication or session ids will persist between requests as well.
First off a sample page to call. This sets a cookie containing the current time if no such cookie has been set. It also shows the value of the cookie in the output. View this page in the browser and it'll have the current time. Keep refreshing and the time doesn't change.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CookieTest.aspx.cs" Inherits="WebApplication1.CookieTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= Request.Cookies["TestCookie"] == null ? "" : Request.Cookies["TestCookie"].Value %>
</div>
</form>
</body>
</html>
public partial class CookieTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["TestCookie"] == null)
{
Response.Cookies.Add(new HttpCookie("TestCookie", DateTime.Now.ToString()));
}
}
}
I'm going to do the sample client as a console app, but the code will work for your winforms app too.
public class CookieAwareWebClient : WebClient
{
public readonly CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = m_container;
}
return request;
}
}
class Program
{
static void Main(string[] args)
{
WebClient clientA = new WebClient();
StreamReader r = new StreamReader(clientA.OpenRead("http://localhost:59466/CookieTest.aspx"));
string html = r.ReadToEnd();
Console.WriteLine("**** REQUEST 1 USING WEBCLIENT ****");
Console.WriteLine(html);
System.Threading.Thread.Sleep(2000);
r = new StreamReader(clientA.OpenRead("http://localhost:59466/CookieTest.aspx"));
html = r.ReadToEnd();
Console.WriteLine("**** REQUEST 2 USING WEBCLIENT ****");
Console.WriteLine(html);
System.Threading.Thread.Sleep(2000);
CookieAwareWebClient clientB = new CookieAwareWebClient();
r = new StreamReader(clientB.OpenRead("http://localhost:59466/CookieTest.aspx"));
html = r.ReadToEnd();
Console.WriteLine("**** REQUEST 1 USING CUSTOMWEBCLIENT ****");
Console.WriteLine(html);
System.Threading.Thread.Sleep(2000);
r = new StreamReader(clientB.OpenRead("http://localhost:59466/CookieTest.aspx"));
html = r.ReadToEnd();
Console.WriteLine("**** REQUEST 2 USING CUSTOMWEBCLIENT ****");
Console.WriteLine(html);
Console.ReadKey();
}
}