Creating your own RSS feed using .NET and WCF
In my previous article I described how to get a syndication feed but what I didn't describe was how to create a syndication feed of your own. In this article I will do just that using the .NET framework.
Firstly here is the method which accepts a collection of articles and creates a syndication feed. The article class should be easily constructed from the code sample below. LINQ in its simplest form is used to construct the syndication feed items; there are many articles on the web which will describe its workings.
public SyndicationFeed GetArticlesAsRss(IEnumerable articles)
{
SyndicationFeed feed = null;
if (articles != null && articles.Count() > 0)
{
const string companyUri = "http://www.avantprime.com";
const string authorUri = "http://www.avantprime.com/about";
const string feedDescription = "Feed description";
const string companyName = "Avant Prime";
const string companyEmail = "_info@avantprime.com";
const string author = "Richard Lee";
const string category = "Technology";
const string title = "Articles";
feed = new SyndicationFeed(companyName, feedDescription, new Uri(companyUri));
feed.Authors.Add(new SyndicationPerson(companyEmail, author, authorUri));
feed.Categories.Add(new SyndicationCategory(category));
feed.Description = new TextSyndicationContent(title);
feed.Items = articles
.Select(article => new SyndicationItem(
article.Title,
article.Content,
article.Url,
article.SeekId.ToString(),
new DateTimeOffset(article.CreatedDate)))
.ToArray();
}
return feed;
}
Secondly output to the browser
ASP.NET MVC
public ActionResult Rss()
{
var articles = ArticleModel.GetLatestArticles(10);
return new RssResult { Feed = GetArticlesAsRss(articles) };
}
To get the RssResult class see the previous article
ASP.NET Webforms
var articles = ArticleModel.GetLatestArticles(10);
var feed = GetArticlesAsRss(articles);
Response.Clear();
Response.ContentType = "application/rss+xml";
Rss20FeedFormatter formatter = new Rss20FeedFormatter(feed);
using (XmlWriter writer = XmlWriter.Create(Response.Output))
{
formatter.WriteTo(writer);
}
Response.Flush();
Response.End();
Please feel free to post your comments.
2011/10/09 13:05 1BCome on, my friend! Try it ,I like .net from PHP. you know that,PHP is so easy for can't study cpumoter language'human. And, yes you can do it, you can move all you wordpress posts into other blog,couse I fand an posts can help you, but is Chinese. ()