我正在寻找一种方法来使用网址获取网页的内容。例如,当您访问www.example.com时,您会看到文本“hello world”。我想在razor c#中获取文本hello world。
换句话说,我需要使用c#替换以下jquery代码:
$.post("www.example.com",{},function(data){
useme(data);
})
var html = Html.Raw(new System.Net.WebClient().DownloadString("http://www.example.com"));
Html.Raw
允许解析为HTML,而WebClient
的新实例可以帮助直接获取字符串。
您可以使用WebClient class DownloadString方法获取远程页面的内容:
using (var client = new WebClient()){
var response = client.DownloadString("http://www.example.com");
// process response
}
如果响应类型是text/plain
,则应该只获得“Hello World”,但响应类型为text/html
,则需要解析文本。你可以使用HtmlAgilityPack。