This is a mirror of official site: http://jasper-net.blogspot.com/

Building an RSS Feed in ASP.NET MVC

| Sunday, April 18, 2010
When building a website it is common to expose an RSS/ATOM feed for your content. Feeds serve two main purposes. The first, is that it allows other sites to consume your content for syndication. For example if you write .NET articles, there may be other partner sites that subscribe to your feed and dynamically pull in your content.  Secondly, feeds allow users to subscribe to your site so they can get notifications when your content is updated. This is especially relevant for sites with irregular content updates such as a personal blog.

In the .NET 3.5 framework there is a namespace titled System.ServiceModel.Syndication which very few people seem to know about. The classes contained in this library allows you to create and consume RSS feeds with minimal effort. I recently created a feed for my WeBlog application. I was astonished about how little time it took to implement an RSS Feed. Instead of weighing you down with all the details...I'll let the code do the talking:

public ActionResult Feed( int? page, int? pageSize ) {
   var query = from x in Engine.Posts.FindPosts( page, pageSize )
               where
                   x.PublishDate != null
               orderby
                   x.PublishDate descending
               select x;

   List<PostModel> posts = query.ToList();
   Uri site = new Uri(Engine.GetWebAppRoot());
   SyndicationFeed feed = new SyndicationFeed(Engine.Settings.SiteName, Engine.Settings.SiteDescription, site );
   List<SyndicationItem> items = new List<SyndicationItem>();
   foreach( PostModel post in posts ) {
       SyndicationItem item = new SyndicationItem(post.Title, post.Content,
           new Uri( Engine.GetWebAppRoot() + "/Posts/" + post.Slug), post.ID.ToString(), post.PublishDate ?? DateTime.Now);
       items.Add(item);
   }
   feed.Items = items;
   return new Core.RSSActionResult() { Feed = feed };
}

Read more: Code Capers

Posted via email from jasper22's posterous

0 comments: