在HttpWebRequest中关闭自动重定向

时间:2016-03-17 22:27:43

标签: c# http cookies windows-phone-8.1

我有一个POST请求,返回代码302。

string FormParams = "Some_string";
byte[] SomeBytes = Encoding.UTF8.GetBytes(FormParams);

HttpWebRequest AuthPost = (HttpWebRequest)WebRequest.Create("https://example.com/");
AuthPost.Method = "POST";
AuthPost.AllowAutoRedirect = false;

AuthPost.Accept = "text/html, application/xhtml+xml, */*";
AuthPost.Headers["Referer"] = "https://example.com/";
AuthPost.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; ASU2JS; rv:11.0) like Gecko";
AuthPost.ContentType = "application/x-www-form-urlencoded";
AuthPost.Headers["Accept-Encoding"] = "gzip, deflate";
AuthPost.Headers["DNT"] = "1";
AuthPost.Headers["Connection"] = "Keep-Alive";
AuthPost.Headers["Cookie"] = savedcookie;
AuthPost.Headers["Content-Length"] = SomeBytes.Length.ToString();
AuthPost.Headers["Cache-Control"] = "no-cache";
Stream postStream = await AuthPost.GetRequestStreamAsync();
postStream.Write(SomeBytes, 0, SomeBytes.Length);
postStream.Flush();

HttpWebResponse AuthPostResponse = (HttpWebResponse)await AuthPost.GetResponseAsync();

所以我需要在重定向之前管理返回的cookie。 如何关闭自动重定向或管理Cookie?

1 个答案:

答案 0 :(得分:0)

使用CookieContainer属性/类。见MSDN

CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer; 

您可以在其他请求中重复使用容器。