[英]How to get the webpage source in ASP.NET C#?
How can I get the HTML code of a page in C# ASP.NET? 如何在C#ASP.NET中获取页面的HTML代码?
Example: http://google.com
示例:
http://google.com
: http://google.com
How I can get this HTML code by ASP.NET C#? 我如何通过ASP.NET C#获取此HTML代码?
The WebClient
class will do what you want: WebClient
类将执行您想要的操作:
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: 如评论中所述,您可能更喜欢使用
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;
}
}
MSDN example of HttpWebrequest.GetResponse has working code. HttpWebrequest.GetResponse的MSDN示例具有工作代码。
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
如果问题是“如何获取网页的代码隐藏文件”,答案是否定的。
If you are planning to do a lot of web requests to access RESTful services, be careful with the HttpWebRequest
object. 如果您计划执行大量Web请求来访问RESTful服务,请注意
HttpWebRequest
对象。 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. 如果您动态加载其他页面,我建议您使用JavaScript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.