Question about the environment used by HttpWebRequest when making
requests:
When I use IE to browse a site, all of my cookies, etc. are available
as part of the request. However, when I make that same request using
HttpWebRequest, all of the cookies that I have are not available as
part of the request.
Is there a way to change that - I want all of the cookies that the
site has set to be available. If there is no way to change it, what
are my other options?
Here's a simple repro.
1. Go to this page: http://www.battagin.com/dan/temp/cookiedemo.asp
2. Enter a value in the textbox and click submit. It will be set as
a cookie on your machine, and will display in the page under the
textbox. NOTE: close your browser and re-navigate to the page to
ensure that it persists.
3. Create an HttpWebRequest to the page and look at the HTML that
comes back (code below)
4. Result: The cookie value is not in the HTML.
Thanks,
-Dan
Sample code:
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Net;
namespace CookieDemo {
public class Form1 : Form {
TextBox _txt1 = new TextBox();
TextBox _txt2 = new TextBox();
Button _cmd = new Button();
public Form1() {
_txt1.Location = new Point(5, 5);
_txt1.Size = new Size(315, 20);
_txt1.Text =
"http://www.battagin.com/dan/temp/cookiedemo.asp";
_txt2.Location = new Point(5, 30);
_txt2.Multiline = true;
_txt2.ScrollBars = ScrollBars.Vertical;
_txt2.Size = new Size(400, 230);
_cmd.Location = new Point(330, 5);
_cmd.Text = "Go";
_cmd.Click += new EventHandler(_cmd_Click);
this.Text = "CookieDemo";
this.ClientSize = new Size(412, 266);
this.Controls.AddRange(new Control[] {_cmd,
_txt2, _txt1});
}
[STAThread]
static void Main() {
Application.Run(new Form1());
}
private void _cmd_Click(object sender, EventArgs e) {
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create(_txt1.Text);
WebResponse resp = req.GetResponse();
_txt2.Text = new
StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd();
}
}
}