NET 框架公开了处理聚合的类: SyndicationFeed 等等。
So instead of doing the rendering yourself or using some other suggested RSS library why not let the framework take care of it?
基本上,你只需要下面的自定义 ActionResult,然后就可以开始了:
public class RssActionResult : ActionResult
{
public SyndicationFeed Feed { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/rss+xml";
Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);
using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
{
rssFormatter.WriteTo(writer);
}
}
}
现在,在您的控制器操作中,您可以简单地返回以下内容:
return new RssActionResult() { Feed = myFeedInstance };
using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace MVC3JavaScript_3_2012.Rss
{
public class RssFeed : FileResult
{
private Uri _currentUrl;
private readonly string _title;
private readonly string _description;
private readonly List<SyndicationItem> _items;
public RssFeed(string contentType, string title, string description, List<SyndicationItem> items)
: base(contentType)
{
_title = title;
_description = description;
_items = items;
}
protected override void WriteFile(HttpResponseBase response)
{
var feed = new SyndicationFeed(title: this._title, description: _description, feedAlternateLink: _currentUrl,
items: this._items);
var formatter = new Rss20FeedFormatter(feed);
using (var writer = XmlWriter.Create(response.Output))
{
formatter.WriteTo(writer);
}
}
public override void ExecuteResult(ControllerContext context)
{
_currentUrl = context.RequestContext.HttpContext.Request.Url;
base.ExecuteResult(context);
}
}
}
还有控制密码。
[HttpGet]
public ActionResult RssFeed()
{
var items = new List<SyndicationItem>();
for (int i = 0; i < 20; i++)
{
var item = new SyndicationItem()
{
Id = Guid.NewGuid().ToString(),
Title = SyndicationContent.CreatePlaintextContent(String.Format("My Title {0}", Guid.NewGuid())),
Content = SyndicationContent.CreateHtmlContent("Content The stuff."),
PublishDate = DateTime.Now
};
item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri("http://www.google.com")));//Nothing alternate about it. It is the MAIN link for the item.
items.Add(item);
}
return new RssFeed(title: "Greatness",
items: items,
contentType: "application/rss+xml",
description: String.Format("Sooper Dooper {0}", Guid.NewGuid()));
}