Created
September 29, 2011 08:04
-
-
Save TowardsDeath/1250247 to your computer and use it in GitHub Desktop.
RSS with MVC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.ServiceModel.Syndication; | |
using System.Web.Mvc; | |
using System.Xml; | |
namespace Web | |
{ | |
public class RssController : Controller | |
{ | |
public ActionResult Articles() | |
{ | |
var articles = ...; // Retrieve articles from DB. | |
var items = ( from a in articles | |
select new SyndicationItem( | |
a.Title, | |
a.Contents, | |
new Uri( "http://site/articlelink" ), | |
a.Id.ToString(), | |
a.PostDate | |
) ); | |
var feed = new SyndicationFeed( "Feed title", "Feed description", new Uri( "http://site/feed" ), items ); | |
return new RssResult { Feed = feed }; | |
} | |
} | |
/// <summary> | |
/// Represents a class that is used by an action to render an RSS feed. | |
/// </summary> | |
public class RssResult : ActionResult | |
{ | |
/// <summary> | |
/// Gets or sets the feed with items. | |
/// </summary> | |
public SyndicationFeed Feed { get; set; } | |
/// <summary> | |
/// Turns the feed items into RSS XML that can be used for syndication. | |
/// </summary> | |
/// <param name="context">The context of the controller in which the result is executed.</param> | |
public override void ExecuteResult( ControllerContext context ) | |
{ | |
context.HttpContext.Response.ContentType = "application/rss+xml"; | |
using( var writer = XmlWriter.Create( context.HttpContext.Response.Output ) ) | |
{ | |
var rssFormatter = new Rss20FeedFormatter( this.Feed ); | |
rssFormatter.WriteTo( writer ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment