gpt4 book ai didi

c# - 如何向 WebRequest 添加 cookie?

转载 作者:IT王子 更新时间:2023-10-29 04:16:30 25 4
gpt4 key购买 nike

我正在尝试对一些代码进行单元测试,我需要替换它:

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

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

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

最佳答案

根据您的评论,您可能会考虑写一个 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;
}

然后你可以有这样的代码:

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

关于c# - 如何向 WebRequest 添加 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11164275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com