Recently I was tasked with adding a list of recent blog posts from our WordPress site inside of an ASP.NET MVC web site. The initial strategy was going to involve fetching from the RSS feed, but after discovering the WordPress supported XML-RPC, I decided to explore that route first.
Using XML-RPC was supposed to be easy considering there is an available .NET library for it created by Charles Cook. The task should have been further simplified because there are several C# WordPress wrappers available.
After spending time with a couple of the WordPress wrappers available, it quickly became clear that the process of updating the wrappers to comply with the latest version of WordPress would be far more work than it was worth; especially considering the scope of this task.
So it was back to the original strategy of creating an RSS reader specifically for WordPress. After digging around a bit, I thankfully stumbled across the Syndication Feed class that is available in .Net 4.0 and above.
The Syndication Feed class basically provides the quick and easy solution that I was looking for while exploring the XML-RPC route. It really turned out to be a lot easier than I thought it could ever be.
So let’s get started. For this, I will assume that you are using an existing MVC application.
The first step is to add a reference to System.ServiceModel to your project as this is where the Syndication Feed class resides.
The second step is to create a View Model that will define a List of SyndicationItem’s:
[sourcecode language="csharp"]using System.Collections.Generic;using System.ServiceModel.Syndication;namespace MvcApplication1.Models{ public class FeedViewModel { public FeedViewModel() { Posts = new List<SyndicationItem>(); } public List<SyndicationItem> Posts { get; set; } }}[/sourcecode]
And in the Controller, we will need to populate the list:
[sourcecode language="csharp"]using System.Linq;using System.Web.Mvc;using System.ServiceModel.Syndication;using System.Xml;using MvcApplication1.Models;namespace MvcApplication1.Controllers{ public class HomeController : Controller { public ActionResult Index() { var model = new FeedViewModel(); using (var reader = XmlReader.Create("http://blog.yojimbocorp.com/feed/")) { var feed = SyndicationFeed.Load(reader); foreach (var post in feed.Items.Take(10)) { model.Posts.Add(post); } } return View(model); } }}[/sourcecode]
You will of course want to customize the reader URL to be your own and most likely will want to create a configuration entry for it.
And finally, display the data in your view:
[sourcecode language="html"]@model MvcApplication1.Models.FeedViewModel @foreach (var post in Model.Posts){ <td><a href="@post.Id" target="_blank">@Html.DisplayFor(model => post.Title.Text)</a></td><br /> }[/sourcecode]
I highly recommend reviewing the SyndicationItem documentation when creating your view.