【问题标题】:how to maintaine cookies in between two Url's in asp.net如何在asp.net中的两个Urls之间维护cookie
【发布时间】:2011-06-28 06:43:36
【问题描述】:

我需要将 cookie 值传递给另一个具有相同域的 Url。我有两个具有相同域名的 url。一个用于身份验证的 Url 另一个用于检索数据。我首先执行了经过身份验证的 url。使用此身份验证 cookie,我想执行第二个 url ..

如何做到这一点...我无法将 cookie 添加到 socond url

这是我的代码..

字符串 url = "http://172.16.xx.xxx:8080/cms?login&username=santhu&password=welcome"; 字符串 url1 = "http://172.16.xx.xxx:8080//cms?status=ProcessStatus"; 字符串结果 = null;

    try
    {
        WebClient client = new WebClient();
        WebClient client1 = new WebClient();
        result = client.DownloadString(url);
        TextBox1.Text = result.ToString();

        if (Response.Cookies["JSESSIONID"] != null)
            TextBox1.Text = Server.HtmlEncode(Response.Cookies["JSESSIONID"].Value);             

            client1.Headers.Add("JSESSIONID", TextBox1.Text);
            result = client1.DownloadString(url1);
            TextBox2.Text = result.ToString();

    }
    catch (Exception ex)
    {

    }

【问题讨论】:

    标签: c# asp.net cookies


    【解决方案1】:

    设置cookie.Domain = "domain.com",它适用于该域的所有网址。

    【讨论】:

      【解决方案2】:

      您可以尝试以下方法。定义一个 cookie 感知网络客户端:

      public class WebClientEx : WebClient
      {
          public CookieContainer CookieContainer { get; private set; }
      
          public WebClientEx()
          {
              CookieContainer = new CookieContainer();
          }
      
          protected override WebRequest GetWebRequest(Uri address)
          {
              var request = base.GetWebRequest(address);
              if (request is HttpWebRequest)
              {
                  (request as HttpWebRequest).CookieContainer = CookieContainer;
              }
              return request;
          }
      }
      

      然后将此客户端用于两个请求:

      using (var client = new WebClientEx())
      {
          var values = new NameValueCollection
          {
              { "username", "santhu" },
              { "password", "welcome" },
          };
          // Authenticate
          client.UploadValues("http://172.16.xx.xxx:8080/cms?login", values);
      
          // Download some secure resource
          var result = client.DownloadString("http://172.16.xx.xxx:8080//cms?status=ProcessStatus");
      }
      

      【讨论】:

      • @santhosh,如果回答对您有帮助,请点击 marking it as such 旁边的勾号。
      猜你喜欢
      • 2014-03-12
      • 2011-10-26
      • 2010-11-29
      • 2011-09-21
      • 2019-11-08
      • 2012-04-14
      • 2011-04-12
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多