简体   繁体   English

如何将 cookie 添加到 WebRequest?

[英]How to add cookies to WebRequest?

I am trying to unit test some code, and I need to to replace this:我正在尝试对一些代码进行单元测试,我需要替换它:

  HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create( uri );
  httpWebRequest.CookieContainer = new CookieContainer();

with

  WebRequest webRequest = WebRequest.Create( uri );
  webRequest.CookieContainer = new CookieContainer(); 

Basically, how do I get cookies into the request without using a HttpWebRequest?基本上,如何在不使用 HttpWebRequest 的情况下将 cookie 放入请求中?

Based on your comments, you might consider writing an extension method :根据您的评论,您可以考虑编写扩展方法

public static bool TryAddCookie(this WebRequest webRequest, Cookie cookie)
{
    HttpWebRequest httpRequest = webRequest as HttpWebRequest;
    if (httpRequest == null)
    {
        return false;
    }

    if (httpRequest.CookieContainer == null)
    {
        httpRequest.CookieContainer = new CookieContainer();
    }

    httpRequest.CookieContainer.Add(cookie);
    return true;
}

Then you can have code like:然后你可以有这样的代码:

WebRequest webRequest = WebRequest.Create( uri );
webRequest.TryAddCookie(new Cookie("someName","someValue"));

WebRequest is an abstract class that does not have a CookieContainer property. WebRequest 是一个没有 CookieContainer 属性的抽象类。 In addition you can't use the Headers collection (not implemented exception) so any attempt like webRequest.Headers.Add("Cookie", "...") will fail.此外,您不能使用 Headers 集合(未实现的异常),因此任何类似 webRequest.Headers.Add("Cookie", "...") 的尝试都将失败。

Sorry, but you have no chance to use cookies with WebRequest.抱歉,您没有机会在 WebRequest 中使用 cookie。

Stick on HttpWebRequest and add/edit as many cookies you like using its Headers collection!坚持使用 HttpWebRequest 并使用其 Headers 集合添加/编辑您喜欢的任意数量的 cookie!

Try with something like this:尝试这样的事情:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/default.html");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Cookie("ConstoCookie", "Chocolate Flavour"));

dlev's answer ended up working, but I had problems implementing the solution ("The parameter '{0}' cannot be an empty string."), so I decided to write the full code in case anybody else has similar problems. dlev 的回答最终奏效了,但我在实施该解决方案时遇到了问题(“参数‘{0}’不能是空字符串。”),因此我决定编写完整代码,以防其他人遇到类似问题。

My goal was to get the html as a string, but I needed to add the cookies to the web request.我的目标是将 html 作为字符串获取,但我需要将 cookie 添加到 Web 请求中。 This is the function that downloads the string using the cookies:这是使用 cookie 下载字符串的函数:

public static string DownloadString(string url, Encoding encoding, IDictionary<string, string> cookieNameValues)
{
    using (var webClient = new WebClient())
    {
        var uri = new Uri(url);
        var webRequest = WebRequest.Create(uri);
        foreach(var nameValue in cookieNameValues)
        {
            webRequest.TryAddCookie(new Cookie(nameValue.Key, nameValue.Value, "/", uri.Host));
        }                
        var response = webRequest.GetResponse();
        var receiveStream = response.GetResponseStream();
        var readStream = new StreamReader(receiveStream, encoding);
        var htmlCode = readStream.ReadToEnd();                
        return htmlCode;
    }
}   

We are using the code from dlev's answer:我们正在使用 dlev 的答案中的代码:

public static bool TryAddCookie(this WebRequest webRequest, Cookie cookie)
{
    HttpWebRequest httpRequest = webRequest as HttpWebRequest;
    if (httpRequest == null)
    {
        return false;
    }

    if (httpRequest.CookieContainer == null)
    {
        httpRequest.CookieContainer = new CookieContainer();
    }

    httpRequest.CookieContainer.Add(cookie);
    return true;
}

This is how you use the full code:这是您使用完整代码的方式:

var cookieNameValues = new Dictionary<string, string>();
cookieNameValues.Add("varName", "varValue");
var htmlResult = DownloadString(url, Encoding.UTF8, cookieNameValues);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM