Creating a simple RSS feed using ASP.NET MVC

Posted by William on Oct 8, 2009

Looking to serve an rss document via your ASP.NET MVC controller? Here is a simple, quick means to do so. If you are looking for a much neater, smarter, reusable method of serving rss from your controllers check out my ASP.NET MVC RssResult post (coming soon).

For the demonstrations below I will be using a generic List<News>. News is a simple class with common news properties, we will be using Title, Description and Url. Although you can change the view to handle your own model easily enough.

Create a view named Feed, as you would normally for an HTML view. However, in this case change the ContentType property to “text/xml”. Sample code is listed below. Notice the <?xml tag is butted up against the page declaration. This is necessary because an xml document’s first character must be the beginning of the doctype declaration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
<%@ Page Language="C#" ="text/xml" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Domain.Model.News>>" %><?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>William Duffy's News</title>
    <link>http://www.wduffy.co.uk</link>
    <description>The latest news and stuff from the exciting life of William Duffy</description>
    <% foreach (var news in Model) { %>
    <item>
      <title><%= news.Title %></title>
      <link>http://www.wduffy.co.uk/News/Details/<%= news.Url %></link>
      <description><%= news.Description %></description>
    </item>
    <% } %>
  </channel>
</rss>

In your controller, pass the IEnumerable collection of items that are to be represented in the rss document to the view.

 
public ActionResult Feed()
{
    NewsCollection news = new NewsService().GetByLatest();
    return View(news);
}

And that’s it. You can now request your rss document at http://www.yourdomain.com/Controller/Feed.