c# - Cookie 和 C# HttpWebRequest

标签 c# http web cookies

我一直在尝试登录到服务器以获取身份验证 cookie( session cookie),然后我可以将其用于对服务器的进一步调用。我读过的每个例子都遵循相同的模式:

HttpWebRequest request = WebRequest.Create(loginURL) as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;

var cookies = response.Cookies;

这对我不起作用,因为 cookies 变量最终为空,调试分析显示 response.Cookies 为空。服务器是我的,我通过调试可以看到正在设置cookie。如果我用它登录到我的网站,我也可以在 Firefox 中看到 cookie。所以我知道正在设置 cookie。

经过一番摸索,我发现 cookie 是在请求 中设置的,而不是在响应中。所以下面的代码有效。我的问题是:为什么?为什么填充请求而不是响应?这与成为职位有关,而不是获得吗?我完全感到困惑。

    private void Login()
    {
        string userName = UserNameText.Text;
        string password = PasswordText.Password;
        string baseURL = URLText.Text;

        string loginURL = baseURL + "/Authentication/LoginAction";

        HttpWebRequest request = WebRequest.Create(loginURL) as HttpWebRequest;
        request.Method = "POST";

        string formContent =
            "UserName=" + userName +
            "&Password=" + password;

        var byteArray = Encoding.UTF8.GetBytes(formContent);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;
        request.CookieContainer = new CookieContainer();

        try
        {
            using (var dataStream = request.GetRequestStream())
            {

                dataStream.Write(byteArray, 0, byteArray.Length);

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    var cookies = request.CookieContainer;

                    if (cookies.Count != 0)
                    {
                        cookies_ = cookies;
                    }
                }
            }
        }
        catch(Exception ex)
        {
            // don't bother too much
            Debug.WriteLine(ex.Message);
        }
    }

最佳答案

CookieContainer 应被视为类似于特定站点的浏览器 cookie 缓存。这个想法是您提供容器作为请求的一部分,然后它由您收到的 cookie 填充,您可以为后续请求重用该容器。当您发出请求时,容器中的 cookie 会随请求一起发送(就像浏览器会使用存储的 cookie 一样)。

因此,例如,如果您有一个使用 cookie 来存储身份验证 token 的页面,您可以将 cookie 容器与登录请求一起传递,然后将其与需要经过身份验证的 cookie 的后续请求一起传递。

至于为什么你不能简单地从请求中提取它,我猜 Microsoft 只是不想在你可以在请求中传递对可变 cookie 容器的引用时复制东西。

关于c# - Cookie 和 C# HttpWebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867864/

相关文章:

asp.net - 如果我的网站是 HTTPS,是否每次调用数据或静态页面也必须是 HTTPS?

javascript - ExtJS 4 - 访问 REST 代理和/或存储中的自定义响应 header ?

python - 类型错误... 'myModel' 对象不可迭代

c# - 当我使用 x :bind in uwp: invalid binding path err 时出错

从 Http 到 Socks 的 C# 隧道/桥接

c# - 为什么 File.WriteAllText() 通过添加逗号来格式化我的数字?

android - 当我想要获取包抖动时,它显示 HTTP 错误 403 : Forbidden

c# - 通过 WPF 中 ViewModel 中的命令将 UserControl 添加到 Canvas

apache - htaccess文件中继承的RewriteOptions有什么作用?

mongodb - 玩!添加reactivemongo插件后框架 Controller 返回EMPTY RESPONSE