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

2条回答
看我几分像从前
2楼-- · 2019-08-14 15:45
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; ");
查看更多
时光不老,我们不散
3楼-- · 2019-08-14 15:53

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

查看更多
登录 后发表回答