【问题标题】:How maintain session beetween two Url in asp. Netasp中如何维护两个Url之间的会话网
【发布时间】:2011-09-21 01:10:40
【问题描述】:

我有两个 URl。如果我打开第一个 url,它将允许我们进行身份验证。第二个 URL 将 Web 内容作为 XML 数据打开。我需要读取该数据...但是当我执行第一个 URL 时,它的工作正常 Authentication 是 SUCCESS,但是我立即尝试打开第二个 URL,它说 Authentication failed 。如何保持从第一个 URL 到第二个 URL 的会话...

我的代码:

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

【问题讨论】:

  • 使用 Session[""] 变量来维护值还是 Cookie?
  • 好的,我维护会话值,但是如何将该会话呈现到第二个 url..知道已经通过身份验证..
  • 请尝试解决我被吊死在这里...

标签: c# asp.net-session


【解决方案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;
    }
}

否则,您可以通过使用 Firebug 手动添加值来解决问题 :)

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

【讨论】:

    【解决方案2】:

    您需要记住第一个请求中的“Set-Cookie”响应标头,并在您的第二个请求中发送它。

    基本上,在第一个请求之后(可能在 DownloadString() 之后,您需要在 client.ResponseHeaders 中找到标头,然后您需要以某种方式将其添加到 client.Headers

    编辑:好像上面是不可能的,但你可以修改底层的 WebRequest 实例,看到这个问题:How can I get the WebClient to use Cookies?

    或者这个:http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2011-04-12
    • 2012-08-01
    • 2010-11-20
    • 2014-04-19
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多