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

2019-06-25 04:20发布

问题:

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.