怎么利用C#中的 webclient 创建cookie

Cookies are not limited only to web browsers. any http-aware client that supports cookies can deal with a cookie sending aSp .net Web api. the following code example shows a class extended from WebClient. it overrides the virtual method GetWebRequest to attach an instance of CookieContainer to the request. the CookieContainer object instance has to be reused across the requests to let it push cookies in the subsequent requests. For this reason, it is a class-level field and the same instance of the web client is used to send multiple requests. here we use a proxy of address localhost and port 8888, that of Fiddler, to inspect requests and responses.

复制代码
public class CookieWebClient : WebClient
{
    private CookieContainer jar = new CookieContainer();
    protected override WebRequest GetWebRequest(Uri address)
    {

        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
            webRequest.CookieContainer = jar;
        return request;
    }
}
public class TestClass
{
    public void MyTestMethod()
    {
        string url = "http://localhost:7077/api/employees/12345";

        CookieWebClient client = new CookieWebClient()
        {
            Proxy = new WebProxy("localhost", 8888)    // Fiddler 
        };
        Console.WriteLine(client.DownloadString(url)); //  In this request, the cookie gets sent back to the web API
    }
}
复制代码

 

posted @   iDEAAM  阅读(2071)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
历史上的今天:
2014-09-11 Microsoft Dynamics CRM 2011 面向Internet部署 (IFD) ADFS虚拟机环境搭建的步骤(CRM与ADFS装在同一台服务器上) 摘自网络
2012-09-11 Linq 左连接 内连接
2009-09-11 CSS滤镜使用方法汇总
点击右上角即可分享
微信分享提示