Implementing an rss feed on the codeface … finally

Posted : Tuesday, 29 May 2012 08:34:00

As part of the redesign of this blog, I wanted to incorporate links to various social channels such as LinkedIn, Google+ etc. I also wanted to have an RSS link for my posts as part of the site template which Lousia at CLKDigital skillfully delivered as part of the redesign. I recently started a new job with JellyfishCreative and have been soooooo busy that while I did find the time to update the site to use the template I didn’t get round to actually implementing an RSS feed. Well I found a few minutes at the weekend and have finally got round to it. It was embarrassingly easy. Here’s how it goes…

I created a new ActionResult derived class as follows:

    1 using System.ServiceModel.Syndication;

    2 using System.Web.Mvc;

    3 using System.Xml;


    5 public class RssActionResult : ActionResult

    6 {

    7     private SyndicationFeed _feed;


    9     public RssActionResult(SyndicationFeed feed)

   10     {

   11         _feed = feed;

   12     }


   14     public override void ExecuteResult(ControllerContext context)

   15     {

   16         context.HttpContext.Response.ContentType = "application/rss+xml";


   18         Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(_feed);

   19         using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))

   20         {

   21             rssFormatter.WriteTo(writer);

   22         }

   23     }

   24 }

The purpose of this class is to take an instance of a SyndicationFeed result and write out the contents using a Rss20FeedFormatter class. Both of these feed related classes are located in the System.ServiceModel.Syndication namespace introduced in .Net 3.5.

With the new ActionResult derived class in place I added an action method to my controller, created an instance of SyndicationFeed based on my blog posts using a bit of LINQ and then returned an RssActionResult from the action method supplying the post data as a constructor parameter:

  129 /// <summary>

  130 /// output RSS feed of blog posts.

  131 /// </summary>

  132 /// <returns></returns>

  133 public ActionResult RssFeed()

  134 {

  135     //get last 20 posts

  136     List<BlogPost> feedPosts = Repository.GetRecentPosts(20).ToList();


  138     //publish date is nullable

  139     DateTime lastActivityDate = feedPosts.Select(x => x.PublishDate).Max().GetValueOrDefault(DateTime.MaxValue);


  141     //create feed object

  142     SyndicationFeed feed =

Post a comment Sharespacer

  • (This will not appear on the site)