zoukankan      html  css  js  c++  java
  • 怎么利用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
        }
    }
  • 相关阅读:
    排序算法研究
    SqlParameters参数
    winfrom项目
    方法参数中有out和in关键字是什么意思?
    在C#中使用存储过程
    11Book系列多表群操作
    7drf过滤排序分页异常处理
    12RBAC基于角色的访问控制
    5drf路由组件
    8drf自动生成接口文档
  • 原文地址:https://www.cnblogs.com/haoliansheng/p/4802279.html
Copyright © 2011-2022 走看看