'c# WebRequest cookies not working

I am trying to get my c# console application to check if the credentials supplied are correct. But when I try it the web page gives a error:

<div id="login_error">  <strong>ERROR</strong>: Cookies are blocked or not supported by your browser. You must <a href="https://codex.wordpress.org/Cookies">enable cookies</a> to use WordPress.<br />

This is my code:

     static bool SendRequest(string Username, string Password, string URL) {

        string formUrl = URL; 
        string formParams = string.Format("log={0}&pwd={1}&wp-submit={2}&redirect_to={3}&testcookie={4}", Username, Password, "Log In", "http://localhost/wp-admin/", "1");
        string cookieHeader;
        WebRequest req = WebRequest.Create(formUrl);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);
        req.ContentLength = bytes.Length;
        ((HttpWebRequest)req).CookieContainer = new CookieContainer();
        using (Stream os = req.GetRequestStream())
        {
            os.Write(bytes, 0, bytes.Length);
        }
        WebResponse resp = req.GetResponse();
        cookieHeader = resp.Headers["Set-cookie"];

        string pageSource;

        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            pageSource = sr.ReadToEnd();
        }

        Console.Write(pageSource);

        return true;
    }

I think the problem is that the cookies are not working but I have no clue how to fix this.

All help is appreciated!



Solution 1:[1]

You're not setting a CookieContainer to your HttpWebRequest, thus the default is set to null which means the client won't accept cookies.

CookieContainer from MSDN

The CookieContainer property provides an instance of the CookieContainer class that contains the cookies associated with this request.

CookieContainer is null by default. You must assign a CookieContainer object to the property to have cookies returned in the Cookies property of the HttpWebResponse returned by the GetResponse method.

You must set a new CookieContainer before getting a response from the server.

req.ContentLength = bytes.Length;
((HttpWebRequest)req).CookieContainer = new CookieContainer();
// Rest of the code here..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Orel Eraki