How to get the webpage source in ASP.NET C#?

こ雲淡風輕ζ 提交于 2019-12-10 15:51:48

问题


How can I get the HTML code of a page in C# ASP.NET?

Example: http://google.com

How I can get this HTML code by ASP.NET C#?


回答1:


The WebClient class will do what you want:

string address = "http://stackoverflow.com/";   

using (WebClient wc = new WebClient())
{
    string content = wc.DownloadString(address);
}

As mentioned in the comments, you might prefer to use the async version of DownloadString to avoid blocking:

string address = "http://stackoverflow.com/";

using (WebClient wc = new WebClient())
{
    wc.DownloadStringCompleted +=
        new DownloadStringCompletedEventHandler(DownloadCompleted);
    wc.DownloadStringAsync(new Uri(address));
}

// ...

void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if ((e.Error == null) && !e.Cancelled)
    {
        string content = e.Result;
    }
}



回答2:


MSDN example of HttpWebrequest.GetResponse has working code.

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx




回答3:


If the question is "How to get the code-behind file of a web page", the answer is no.




回答4:


If you are planning to do a lot of web requests to access RESTful services, be careful with the HttpWebRequest object. It takes a while to be reclaimed, and if you have enough traffic (just a few calls a minute), you can start to get strange behavior.

If you are loading other pages dynamically, I'd recommend doing it in JavaScript.



来源:https://stackoverflow.com/questions/1820991/how-to-get-the-webpage-source-in-asp-net-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!