使用ASP.NET MVC 3检索和缓存HTML从网站 [英] Retrieving and caching HTML from website using ASP.NET MVC 3

查看:122
本文介绍了使用ASP.NET MVC 3检索和缓存HTML从网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个网站,是不是我的控制之下显示某些东西的局部视图。
网站上的数据只能通过HTML,所以我只能通过查询网站,并解析HTML检索。 (该网站拥有50个元素的列表,而我只想要进入前10)
现在,从网站的数据没有变化非常频繁,因此我想,我可以检索按小时计算的HTML,并在我的网站显示缓存版本。

I want a partial view that display some stuff from a website that is not under my control. The data on the website is only available through HTML, and thus I can only retrieve it by querying the web site and parsing the HTML. (The website holds a list of 50 elements, and I only want the top 10.) Now, the data from the website is not changing very frequently, so I imagine that I can retrieve the HTML on an hourly basis, and displaying a cached version on my web site.

如何在ASP.NET MVC 3做到这一点?

How can I accomplish this in ASP.NET MVC 3?

推荐答案

这想到的第一个解决方案是创建一个控制器,使一个HTTP请求到远程Web页面并解析你想返回的HTML动作将自己的网页,然后将输出缓存在你的行动。

The first solution that comes to mind is to create an action in a controller that makes an Http request to the remote web page and parses the html you want to return to your own page and then set output caching on your action.

编辑:

什么控制器放在将取决于你的网站的结构和有无局部视图将是对所有的意见或只是一个特定视图中可见的动作。如果部分是在所有视图中显示我要么将其放置在首页的控制器或创建一个常规控制器(如果我预期的要行动将在这样的控制器去)。

What controller to put the action in would depend on the structure of your web site and whether the partial view would be visible on all views or just a specific view. If the partial is visible in all views I'd either place it in the Home controller or create a "General" controller (if I anticipated more actions would go in such a controller).

如果你要处理的结果,我可能会做的列表中选择模型和局部视图。如果你想利用返回的HTML输出的一部分,因为它是我会用同样的方法由马修·雅培答案:

If you want to manipulate the result I would probably make a model and partial view for the list. If you want to take a part of the returned html and output it as it is I would use the same method as in the answer by Matthew Abbott:

return Content(yourHtmlString);

最终会是这个样子:

The end would look something like this:

[OutputCache(Duration = 3600)]
public ActionResult RemoteList()
{
    var client = new WebClient();
    var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com"));

    // Do your manipulation here...

    return Content(html);
}

(上述的一些code被从岗位马修雅培借来的。)

(Some of the above code was borrowed from the post by Matthew Abbott.)

这篇关于使用ASP.NET MVC 3检索和缓存HTML从网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆