c#WebRequest cookie无效

时间:2015-08-17 13:22:45

标签: c# streamreader webrequest

我正在尝试使用我的c#控制台应用程序来检查提供的凭据是否正确。但是当我尝试它时,网页会出错:

<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 />

这是我的代码:

     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;
    }

我认为问题在于cookie无效,但我不知道如何解决这个问题。

感谢所有帮助!

1 个答案:

答案 0 :(得分:4)

您没有为HttpWebRequest设置CookieContainer,因此默认设置为null,这意味着客户端将不接受Cookie。

来自MSDN的CookieContainer

  

CookieContainer属性提供了一个实例   CookieContainer类,包含与此关联的cookie   请求。

     

默认情况下,CookieContainer为 null 。你必须指定一个   CookieContainer对象要在属性中返回cookie   GetResponse返回的HttpWebResponse的Cookies属性   方法

在从服务器获得响应之前,您必须设置一个新的CookieContainer

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