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:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, "Courier New", Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
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.