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

时间:2011-06-28 06:43:37

标签: c# asp.net cookies

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

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

这是我的代码..

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

    }

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

这是你可以尝试的。定义一个支持cookie的Web客户端:

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