如何在asp.net中的两个URL之间维护cookie

问题描述:

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

i need pass the cookie values to another Url which have same domain.i have two url's with same domain name..one Url for Authentication another is for retrieve data.i executed first url its authenticated . with this authentication cookie i want to execute second url ..

如何执行此操作...我无法将cookie添加到第二个URL

How to do this...i unable to Add cookie to 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;
字符串result = null;

string url = "http://172.16.xx.xxx:8080/cms?login&username=santhu&password=welcome"; string url1 = "http://172.16.xx.xxx:8080//cms?status=ProcessStatus"; string result = 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)
    {

    }


以下是您可以尝试的方法。定义一个可识别Cookie的Web客户端:

Here's what you may try. Define a cookie aware web client:

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

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

and then use this client for both requests:

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");
}