Serving up a RSS feed in MVC using WCF Syndication

Posted by brian_ritchie on ASP.net Weblogs See other posts from ASP.net Weblogs or by brian_ritchie
Published on Tue, 22 Feb 2011 03:22:00 GMT Indexed on 2011/02/22 7:25 UTC
Read the original article Hit count: 438

Filed under:
|
|
|

With .NET 3.5, Microsoft added the SyndicationFeed class to WCF for generating ATOM 1.0 & RSS 2.0 feeds.  In .NET 3.5, it lives in System.ServiceModel.Web but was moved into System.ServiceModel in .NET 4.0.

Here's some sample code on constructing a feed:

   1:  SyndicationFeed feed = new SyndicationFeed(title, description, new Uri(link));
   2:  feed.Categories.Add(new SyndicationCategory(category));
   3:  feed.Copyright = new TextSyndicationContent(copyright);
   4:  feed.Language = "en-us";
   5:  feed.Copyright = new TextSyndicationContent(DateTime.Now.Year + " " + ownerName);
   6:  feed.ImageUrl = new Uri(imageUrl);
   7:  feed.LastUpdatedTime = DateTime.Now;
   8:  feed.Authors.Add(new SyndicationPerson() { Name = ownerName, Email = ownerEmail });
   9:   
  10:  var feedItems = new List<SyndicationItem>();
  11:  foreach (var item in Items)
  12:  {
  13:      var sItem = new SyndicationItem(item.title, null, new Uri(link));
  14:      sItem.Summary = new TextSyndicationContent(item.summary);
  15:      sItem.Id = item.id;
  16:      if (item.publishedDate != null)
  17:          sItem.PublishDate = (DateTimeOffset)item.publishedDate;
  18:      sItem.Links.Add(new SyndicationLink() { Title = item.title, Uri = new Uri(link), Length = item.size, MediaType = item.mediaType });
  19:      feedItems.Add(sItem);
  20:  }
  21:  feed.Items = feedItems;

 

Then, we create a custom ContentResult to serialize the feed & stream it to the client:

   1:  public class SyndicationFeedResult : ContentResult
   2:  {
   3:       public SyndicationFeedResult(SyndicationFeed feed)
   4:           : base()
   5:       {
   6:           using (var memstream = new MemoryStream())
   7:           using (var writer = new XmlTextWriter(memstream, System.Text.UTF8Encoding.UTF8))
   8:           {
   9:               feed.SaveAsRss20(writer);
  10:               writer.Flush();
  11:               memstream.Position = 0;
  12:               Content = new StreamReader(memstream).ReadToEnd();
  13:               ContentType = "application/rss+xml" ;
  14:           }
  15:       }
  16:  }


Finally, we wire it up through the controller:

   1:  public class RssController : Controller
   2:  {
   3:      public SyndicationFeedResult Feed()
   4:      {   
   5:          var feed = new SyndicationFeed();
   6:          //  populate feed...
   7:          return new SyndicationFeedResult(feed);
   8:      }
   9:  }

 

In the next post, I'll discuss how to add iTunes markup to the feed to publish it on iTunes as a Podcast.

 

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about c#