Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this code using InternetSetCookie to set cookies at a WebBroser control is not working?

I've done this sample to try to understand why I'm not sending cookies at all with my WebBrowser, it's pretty simple, the form has a WebBrowser on it, that's all:

namespace BrowserTest
{
    public partial class Form1 : Form
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool InternetSetCookie(string url, string name, string data);

        public static bool SetWinINETCookieString(string url, string name, string data)
        {
            return Form1.InternetSetCookie(url, name, data);
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // None of two works
            //SetWinINETCookieString("www.nonexistent.com", null, "dataToTest=thisIsTheData");
            SetWinINETCookieString("www.nonexistent.com", "dataToTest", "thisIsTheData");
            this.webBrowser1.Navigate("www.nonexistent.com");
        }
    }
}

And that's what Fidller says I'm sending:

enter image description here

Looks like everyone using this function succeeds but for the life of me that I cannot get it working. I've tried at different computers and it fails there too. Any help will be great, thanks.

like image 370
Ignacio Soler Garcia Avatar asked Nov 22 '11 19:11

Ignacio Soler Garcia


1 Answers

Just came across this myself.For completeness, you need to check the value returned from InternetSetCookie and if false, call GetLastError which would have given you a return code of 87 - invalid parameter.

i.e.

[DllImport("kernel32.dll")]
public static extern uint GetLastError();

......

bool ok = SetWinINETCookieString("www.nonexistent.com", "dataToTest", "thisIsTheData");
if (!ok)
{
  int errorCode = GetLastError(); //this will return 87  for www.nonexistent.com
}
like image 61
PabloInNZ Avatar answered Sep 21 '22 09:09

PabloInNZ