如何将 cookie 添加到 WebRequest? [英] How to add cookies to WebRequest?

查看:36
本文介绍了如何将 cookie 添加到 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();

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

基本上,如何在不使用 HttpWebRequest 的情况下将 cookie 放入请求中?

Basically, how do I get cookies into the request without using a HttpWebRequest?

推荐答案

根据您的意见,您可能会考虑编写 扩展方法:

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"));

这篇关于如何将 cookie 添加到 WebRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆