How maintain session beetween two Url in asp. Net

2019-08-14 14:53发布

问题:

I have two URl's . If I open first url it will allow us authentication. Second URL will open web content as XML data. I need to read that data... But when I excute first URL its working fine Authentication is SUCCESS, But immediately I try to open second URL its saying Authentication failed . How to maintain session from first URL to second URL...

My Code :

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)
{           
}

回答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;
    }
}

Otherwise you can solve the problem by adding the values manually by using Firebug for cookies :)

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


回答2:

You will need to remember the "Set-Cookie" response header from the first request and send it in your second request.

Basically, after the first request (probably after DownloadString() you would need to find the header in client.ResponseHeaders, and then you would need to add it to client.Headers somehow.

EDIT: Seems like the above isn't possible, but you can modify the underlying WebRequest instance, see this question: How can I get the WebClient to use Cookies?

or this: http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html