如何在asp.net中的两个URL之间维护cookie [英] how to maintaine cookies in between two Url's in asp.net

查看:64
本文介绍了如何在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");
}

这篇关于如何在asp.net中的两个URL之间维护cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆