0

我已经用我的网络浏览器登录了这个网站,每当我尝试打电话时

WebClient myWebClient = new WebClient();
string str = myWebClient.DownloadString("http://localhost/myxml.aspx");
Response.Write(str.ToString());

或者

XmlTextReader reader = new XmlTextReader(url);
while (reader.Read()) {
 Response.Write(reader.ReadOuterXml());
} 

Response.Write 将登录页面返回给我。

是否可以将用户 SessionId 附加到 WebClient 或 XmlTextReader 或者如何使用当前登录的用户请求 C# 中的另一个页面?

4

2 回答 2

1

您需要使用可以处理存储 cookie 的对象。在这种情况下,您将需要该HttpWebRequest课程。您还需要一个CookieContainer来管理身份验证 cookie。

为此,您将:

  1. 创建一个CookieContainer对象(cookie jar),您可以在您发出的每个请求的整个范围内跟踪该对象。
  2. 创建一个HttpWebRequest登录到您正在访问的站点的站点。
  3. CookieContainer您在步骤 1 中创建的每个后续请求都使用。

下面是一个示例,说明如何一起使用HttpWebRequestHttpWebResponseCookieContainer类来发出一个简单的请求,该请求将设置一些 cookie,然后在后续请求中使用这些 cookie。假设一切都是格式良好的标记,其余的应该很容易;)

CookieContainer cookieJar = new CookieContainer();

var webRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
webRequest.CookieContainer = cookieJar;

var webResponse = webRequest.GetResponse();

using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
    Response.Write(reader.ReadToEnd());
}

var anotherWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/search?q=stackoverflow.com");
anotherWebRequest.CookieContainer = cookieJar;

webResponse = anotherWebRequest.GetResponse();

另一种选择(如果您真的想使用WebClient该类)是在您提出请求后解析出ResponseHeaders该类的属性,并在您的下一个请求中包含适当的 cookie。这有点复杂,因为它需要您手动管理 cookie。

由于我假设您希望能够将 Web 响应作为 XML 进行遍历,因此我建议您查看开源库HtmlAgilityPack。它允许您从(很可能)格式不正确或包含某种无效标记的网站发送标记,然后修复无效部分,以便您可以像 XML 一样遍历它。

于 2009-07-03T13:12:05.150 回答
1

在进行一些屏幕抓取时,我遇到了同样的问题。我在 IIS 服务器上请求一个经典 ASP 应用程序(我可以通过服务器响应的一些标头来判断)。我支持正在进行的会话的方式是在 WebClient 上启用 Cookie。它没有切换,您必须继承 WebClient 才能使其工作。

    public class CookieAwareWebClient : WebClient
    {
        protected CookieContainer _container = new CookieContainer();

        public CookieContainer Cookies
        {
            get { return _container; }
            set { _container = value; }
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest httpRequest = base.GetWebRequest(address) as HttpWebRequest;      

            if (httpRequest.CookieContainer != null)
            {
                if (httpRequest != null)
                {
                    CookieCollection newCookies = 
                        GetUniqueCookies(
                                address
                                ,httpRequest.CookieContainer.GetCookies(address)
                                );
                    foreach (Cookie c in newCookies)
                        httpRequest.CookieContainer.Add(c);
                }
            }
            else
                httpRequest.CookieContainer = this.Cookies;

            return (WebRequest)httpRequest;
        }

注意:这不是一个独特的解决方案,我自己在网上找到了这个,但我已经实现了这个解决方案并且效果很好。

于 2009-07-03T13:14:08.110 回答