c# - HttpWebResponse Cookie 未设置重定向

标签 c# cookies httpwebrequest redirectwithcookies

我正在尝试执行以下操作:

  1. 发送 GET 请求以获取登录页面(提示输入用户名、密码并设置 cookie)
  2. 构建一个 POST 请求,从 #1 发送 cookie 和用户名/密码的正文(这将返回一个 Set-Cookie 并重定向到网站的登陆页面以供登录用户使用)

我的问题是 302 重定向。网络服务器返回带有 Set-Cookie 的 302,但是当 HttpWebRequests 自动重定向时,它不会传递现在更新的 cookie。为了解决这个问题,我尝试设置 .AllowAutoRedirect = false,将 cookie 保存在 CookieCollection 中,然后构建第三个 HTTP 请求:GET 到最终的 302 位置。不幸的是,我无法根据此请求设置 cookie。我不确定为什么,这让我发疯。

HTTP 请求按顺序命名为 request、postRequest、redirectRequest。

string loginGetUrl = "https://<..>/signin.htm";
string loginPostUrl = "https://<..>/j_acegi_security_check";
string loginRedirectUrl = "https://<..>/centraladmin/poslinks.htm";

string postData = String.Format("j_username={0}&j_password={1}", username, password);

CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginGetUrl); 
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//Get the response from the server and save the cookies from the first request..
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;        

HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(loginPostUrl);
postRequest.CookieContainer = new CookieContainer();

// Add the received Cookies from the HTTP Get
postRequest.CookieContainer.Add(cookies); 
postRequest.Method = WebRequestMethods.Http.Post;
postRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
postRequest.AllowWriteStreamBuffering = false;
postRequest.ProtocolVersion = HttpVersion.Version11;
postRequest.AllowAutoRedirect = false;
postRequest.ContentType = "application/x-www-form-urlencoded";

byte[] byteArray = Encoding.ASCII.GetBytes(postData);
postRequest.ContentLength = byteArray.Length;
Stream newStream = postRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();

HttpWebResponse postResponse = (HttpWebResponse)postRequest.GetResponse();

// Save the cookies from the POST login request, then send them on to the redirected URL
cookies = postResponse.Cookies;

HttpWebRequest redirectRequest = (HttpWebRequest)WebRequest.Create(loginRedirectUrl);
redirectRequest.CookieContainer = new CookieContainer();

// add cookies from POST
redirectRequest.CookieContainer.Add(cookies);
HttpWebResponse redirectResponse = (HttpWebResponse)redirectRequest.GetResponse();

redirectRequest.CookieContainer.Add(cookies); 处,cookies 对象包含正确的 cookie。但是当我用 Fiddler 查看时,我只看到以下信息:

GET https://<...>/centraladmin/poslinks.htm HTTP/1.1
Host: host:port

在这一点上,我有点撞墙了。有什么建议么?我是在引用错误的东西吗?当心,我通常不写 C# 代码

最佳答案

我无法自己解决这个问题,但确实从 this blog post 中找到了一个有用的代码片段通过@malte-clasen。代码在Github我已将其附在此处以供保留。

我删除了异步组件,因为它在我的代码中不是必需的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DracWake.Core
{
    public class WebClient : IWebClient
    {
        private readonly CookieContainer _cookies = new CookieContainer();

        private HttpWebRequest CreateRequest(Uri uri)
        {
            var request = HttpWebRequest.CreateHttp(uri);
            request.AllowAutoRedirect = false;
            request.CookieContainer = _cookies;
            SetHeaders(request);
            var defaultValidator = System.Net.ServicePointManager.ServerCertificateValidationCallback;
            request.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
                    certificate.Subject.Contains("O=DO_NOT_TRUST, OU=Created by http://www.fiddler2.com")
                    || (certificate.Subject == "CN=DRAC5 default certificate, OU=Remote Access Group, O=Dell Inc., L=Round Rock, S=Texas, C=US")
                    || (defaultValidator != null && defaultValidator(request, certificate, chain, sslPolicyErrors));
            return request;
        }

        private async Task<string> DecodeResponse(HttpWebResponse response)
        {
            foreach (System.Net.Cookie cookie in response.Cookies)
            {
                _cookies.Add(new Uri(response.ResponseUri.GetLeftPart(UriPartial.Authority)), cookie);
            }

            if (response.StatusCode == HttpStatusCode.Redirect)
            {
                var location = response.Headers[HttpResponseHeader.Location];
                if (!string.IsNullOrEmpty(location))
                    return await Get(new Uri(location));
            }   

            var stream = response.GetResponseStream();
            var buffer = new System.IO.MemoryStream();
            var block = new byte[65536];
            var blockLength = 0;
            do{
                blockLength = stream.Read(block, 0, block.Length);
                buffer.Write(block, 0, blockLength);
            }
            while(blockLength == block.Length);

            return Encoding.UTF8.GetString(buffer.GetBuffer());
        }

        public async Task<string> Get(Uri uri)
        {
            var request = CreateRequest(uri);
            var response = (HttpWebResponse) await request.GetResponseAsync();
            return await DecodeResponse(response);
        }

        private void SetHeaders(HttpWebRequest request)
        {
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers[HttpRequestHeader.AcceptLanguage] = "en-US,en;q=0.8,de-DE;q=0.5,de;q=0.3";
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.Headers[HttpRequestHeader.CacheControl] = "no-cache";
        }

        public async Task<string> Post(Uri uri, byte[] data)
        {
            var request = CreateRequest(uri);
            request.Method = "POST";
            request.GetRequestStream().Write(data, 0, data.Length);
            var response = (HttpWebResponse) await request.GetResponseAsync();
            return await DecodeResponse(response);
        }
    }
}

DecodeResponse 解决了我的问题。

关于c# - HttpWebResponse Cookie 未设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21764811/

相关文章:

javascript - Jquery .parent() 获取ID

node.js - 从 cookie 以外的 url 获取 sessionid 是否合理?关于 express-session 的一些事

c# - 有人可以将 C# "HttpWebRequest"转换为 VB6 吗?

c# - 我如何知道必须使用哪些 cookie 才能发出正确的 HttpWebRequest?

c# - c#动态调用方法

c# - 为什么 Float 转换忽略小数点后的零?

c# - 对于带有列表框的用户控件,如何将所选项目公开到父页面?

ruby-on-rails - Restful 认证 : Allow logins from multiple computers?

post - Google Closure 编译 REST Api 突然抛出 Error 405 "Method not allowed"

c# - TcpClient 发送/关闭问题