修复.NET中通过HttpWebRequest 中GET 方法丢失Cookie的bug

最近在项目中通过.NET的 Request.Create 和Request.Respon 进行跨域请求数据,在使用post进行请求是,自己保存的cookie会传递过去,但是通过Get 进行远程服务器请求数据时会丢失Cookie,也不知道为何传递不过去,经过百般搜索找到了一个fixCookies方法,可以把Cookie传递过去,因此记录下来,供大家使用。

public Stream GetStreamDataByGET(string url,HttpContext context)
        {           
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "Get";
            if (!string.IsNullOrEmpty(context.Request.Headers["Cookie"]))
            {
                request.Headers.Add("Cookie", context.Request.Headers["Cookie"]);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            FixCookies(response, context);
            Stream stream = response.GetResponseStream();
            return stream;
        }

        private void FixCookies(HttpWebResponse response, HttpContext context)
        {
            if (response.Headers["Set-Cookie"] == null)
            {
              continue;
             }
                string value = response.Headers.Get("Set-Cookie");
                HttpCookie cc = null;
                foreach (var singleCookie in value.Split(','))
                {
                    Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
                    if (match.Captures.Count == 0)
                    {
                        continue;
                    }
                        context.Response.Headers.Add("Set-Cookie", response.Headers["Set-Cookie"]);
                        cc = new HttpCookie(match.Groups[1].ToString(),match.Groups[2].ToString());
                        context.Response.SetCookie(cc);
                }


        }

你可能感兴趣的:(C#/ASP.NET)