时间:2019-03-17 标签:c#WebRequestcookies不工作

标签 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 不起作用,但我不知道如何解决这个问题。

感谢所有帮助!

最佳答案

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

来自MSDN的CookieContainer

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.

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

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

关于时间:2019-03-17 标签:c#WebRequestcookies不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051574/

相关文章:

c# - 如何签署 Visual Studio .msi 的安装文件

c# - GetType() 是方法还是类?

arrays - 我正在尝试对来自流的字节进行突变,因为进行解码,但是它不起作用

c# - StreamReader.EndOfStream产生IOException

android - UnityWebRequest.SendWebRequest 不在移动设备上发送

c# - WCF 流长度

c# - 注册 'half-closed' 通用组件

c# - 如何获取正则表达式匹配字符串的文件路径?

c# - aws Lambda 函数中的 Webresponse c#

c# - 使用 webrequest 上传文件