Add an RSS feed to an ASP.NET MVC web site by writing 5 simple lines of code

How to impliment an RSS feed in an ASP.NET MVC web application, quickly and easily, simply by returning an RssActionResult.

The best solution currently available to web developers for generating web feeds is to use the built-in syndication libraries of the .NET framework. The best method for delivering the feed is an ASP.NET MVC web app. An ideal solution for data access is provided by the ADO.NET Entity Framework.

Using the .NET framework to set up a feed only takes about five simple lines of code. It took me less than 30 seconds to impliment a feed for records in a table of blog posts on my test site. I pointed Entity Framework at the database and the data access layer and business objects were created or updated automatically. I then wrote 8 lines of code to define an Action which gets some rows from the database (blog posts), passes the data to the syndication library, and then returns it as the result of the action. The .NET framework does everything else, out-of-the-box.

Open up an ASP.NET MVC project in Visual Studio 2008, paste in the code below to add this one Action, and the job is finished. The feed s now implemented. The code is self-explanatory.

Code example: add an RSS feed to an ASP.NET MVC web site by writing 5 simple lines of code

   
public ActionResult Posts()
{
    var feed = new SyndicationFeed(
            "Tim Acheson's blog posts",
            "Posts from Tim Acheson's blog.",
            new Uri(BaseUrl + "Feeds/Blog"),
            BaseUrl + "Feeds/Blog",
            DateTime.Now);
 
    var feedItems =new List<SyndicationItem>();
 
    var posts = blogEntityModel.PostSet.ToList();
 
    for (int i = 0; i < posts.Count; i++)
    {
        var item = new SyndicationItem(
            posts[i].Title,
            posts[i].Body,
            new Uri(BaseUrl + "Blog/" + posts[i].Url),
            BaseUrl + "Blog/" + posts[i].Url,
            posts[i].Created);
        feedItems.Add(item);
    }
 
    feed.Items = feedItems;
 
    return new RssActionResult { Feed = feed };
}

01 February 2009

Share the love:

Comments: 2

Add Comment


Wish there was an equally easy way of getting a list of events out of a DB and exposing them as an iCalendar (http://en.wikipedia.org/wiki/ICalendar) feed. Maybe there is - I just haven't found it yet!

Tim Acheson (29 Jan 11, 11:25)

jamiet, yes, indeed that would be useful! ;) We could write a class that does it. Built-in action responses include Rss, Json and Xml.

Tags:


  • Twitter
  • LinkedIn
  • Facebook
  • Windows Live / Messenger
  • Xbox Live
  • RSS
  • Email