如何在ASP.NET C#中获取网页源代码?

4 c# asp.net methods httpwebrequest

如何在C#ASP.NET中获取页面的HTML代码?

例: http://google.com

我如何通过ASP.NET C#获取此HTML代码?

Luk*_*keH 17

WebClient课程将做你想要什么:

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

using (WebClient wc = new WebClient())
{
    string content = wc.DownloadString(address);
}
Run Code Online (Sandbox Code Playgroud)

正如评论中所提到的,您可能更喜欢使用异步版本DownloadString来避免阻塞:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)