在 MVC ASP.NET 中消费 RSS Feed





5.00/5 (3投票s)
在这篇文章中,我将构建一个 MVC 应用程序来消费 RSS Feed。
引言
在这篇文章中,我将构建一个 MVC 应用程序来消费 RSS Feed。我将修改我之前的项目用于 RSS Feed。请按照以下步骤操作。
选择“Controllers”文件夹,然后右键单击并点击“Controller”,如下所示
按下“添加”,将会创建 RssFeedController
类,如下所示。System.ServiceModel.Syndicatation
中的 SyndicationFeed
类使得处理 RSS Feed 变得容易。下面的代码使用 weblogs.asp.net 的 RSS Feed 来在页面上显示 ASP.NET weblogs。
using System.ServiceModel.Syndication; // add a System.ServiceModel.Web.dll reference
public class RSSFeedController : Controller
{
public ActionResult RSSFeed()
{
string strFeed = "http://weblogs.asp.net/aspnet-team/rss.aspx";
using (XmlReader reader = XmlReader.Create(strFeed))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}
}
}
重复上述步骤 2,并在 Views\RSSFeed 文件夹中添加 RSSFeed 视图。将以下代码添加到 RSSFeed 视图中。
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<SyndicationFeed>" %>
<%@ Import Namespace="System.ServiceModel.Syndication"%>
<asp:Content ID="Content1"
ContentPlaceHolderID="TitleContent" runat="server">
RSSFeed
</asp:Content>
<asp:Content ID="Content2"
ContentPlaceHolderID="MainContent" runat="server">
<h2>RSSFeed</h2>
<% foreach (var item in ViewData.Model.Items)
{
string URL = item.Links[0].Uri.OriginalString;
string Title = item.Title.Text;
Response.Write(string.Format("<p>
<a href=\"{0}\"><b>{1}</b></a>", URL, Title));
Response.Write("<br/>" + item.Summary.Text + "</p>");
} %>
</asp:Content>
现在您可以运行项目,它将显示来自 weblogs.asp.net 的 RSS Feed,如下所示
摘要
在这篇文章中,我们使用 System.ServiceModel.Syndicatation 命名空间
构建了一个 RSS Feed 应用程序。