从 Url 加载页面时出现 C# HtmlAgilityPack TypeAccessException

C# HtmlAgilityPack TypeAccessException when loading page from Url

我正在尝试开发一个 windows phone 应用程序,它将 HTML 页面(通过网络检索)解析为 HTMLDocument 变量并将其用于检查页面,检索值等。即使尝试连接到 BBC News Home page 之类的页面,我也会收到错误消息。

System.TypeAccessException: Attempt by security transparent method 'HtmlAgilityPack.HtmlWeb.LoadFromWebAsync(System.Uri, System.Text.Encoding, System.Net.NetworkCredential)' to access security critical type 'System.Net.NetworkCredential' failed.
   at HtmlAgilityPack.HtmlWeb.LoadFromWebAsync(Uri uri, Encoding encoding, NetworkCredential credentials)
   at HtmlAgilityPack.HtmlWeb.<LoadFromWebAsync>d__0.MoveNext()

此页面不需要凭据,所以我很困惑为什么会遇到此错误。这是代码。

private async Task GetHtmlDocument(string url)
{
    Debug.WriteLine("This is a line");
    try
    {
        HtmlWeb web = new HtmlWeb();
        HtmlDocument rootDocument = await web.LoadFromWebAsync(url);
    }
    catch (Exception e)
    {
        Debug.WriteLine("Exception: " + e);
    }
}

我通过 html-agility-pack 传递 Html 是这样的:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

//cookie if you need
request.CookieContainer = cookie;
//WebRequestMethods.Http.Get
//or WebRequestMethods.Http.Post
request.Method = method;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.Headers.Add("Accept-Language",  "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
request.ServicePoint.Expect100Continue = false;
request.Timeout = 100000;
request.ContentType = "application/x-www-form-urlencoded";

using (WebResponse myResponse = request.GetResponse())
{   
    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
    htmlDoc.OptionFixNestedTags = true;
    htmlDoc.Load(myResponse.GetResponseStream(), Encoding.GetEncoding(1251));
}

然后

string text;

HtmlAgilityPack.HtmlNode node = _doc.DocumentNode.SelectSingleNode(Xpath);
if (node != null) text = node.InnerText;

我正在使用 Windows Phone 8.1,我可能需要在问题中提及。以下是工作。

private async Task GetHtmlDocument(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Credentials = new LoginCredentials().Credentials;

    try
    {
        WebResponse myResponse = await request.GetResponseAsync();
        HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
        htmlDoc.OptionFixNestedTags = true;
        htmlDoc.Load(myResponse.GetResponseStream());
    } catch (...) { ... }
}