如何在asp中维护两个Url之间的会话。净

时间:2011-06-23 08:56:32

标签: c# asp.net-session

我有两个URl。如果我打开第一个网址,它将允许我们进行身份验证。第二个URL将打开Web内容作为XML数据。我需要读取该数据......但是当我执行第一个URL时,其工作正常的身份验证是成功的,但我立即尝试打开第二个URL,其中说身份验证失败。如何保持从第一个URL到第二个URL的会话...

我的代码:

string url1 = "http://172.xx.xx.xx:xxxx/cms?login&username=santhu&password=welcom0e";
string url = "http://172.xx.xx.xx:xxxx//cms?status=ProcessStatus";
string result = null;
string result1 = null;
try
{
  WebClient client = new WebClient();
  result = client.DownloadString(url1);

  TextBox1.Text = result.ToString();
  result1 = client.DownloadString(url);
  TextBox2.Text = result1.ToString();
}
catch (Exception ex)
{           
}

2 个答案:

答案 0 :(得分:1)

private class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient(): this(new CookieContainer())
    {
    }
    public CookieAwareWebClient(CookieContainer c)
    {
        this.CookieContainer = c;
    }
    public CookieContainer CookieContainer { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = this.CookieContainer;
        }
        return request;
    }
}

否则,您可以通过使用Firebug手动添加值来解决问题:)

webClient.Headers.Add("Cookie", "PHPSESSID=xxxxxxx; mosesuser=xxxxxxx; ");

答案 1 :(得分:0)

您需要记住第一个请求中的“Set-Cookie”响应标头,并在第二个请求中发送它。

基本上,在第一个请求之后(可能在DownloadString()之后,您需要在client.ResponseHeaders中找到标题,然后您需要以某种方式将其添加到client.Headers

编辑:似乎上面的内容是不可能的,但您可以修改底层的WebRequest实例,请看这个问题:How can I get the WebClient to use Cookies?

或者:http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html