The following tutorial will show you how to create an RSS Feed in an MVC installation of Umbraco. Using this approach you won’t need to create a template for the page and a macro as in the standard implementation: Setting Up an RSS Feed

Things You Will Need

  1. A document type called ‘RSS Feed’ without a template.
  2. A custom controller, which will handle the RSS Feed document type. (see Custom controllers – Hijacking Umbraco Routes)
  3. A custom action result, which will be returned by the controller and will represent the RSS content.

The ‘RSS Feed’ Document Type

Create a new document type called ‘RSS Feed’, but don’t assign a template. Add two custom properties:

  • Feed Title (textring) – the title for the RSS feed
  • Feed Root (content picker) – the root node for the RSS feed items

The Custom RSS Feed Controller

Create a custom controller called RssFeedController, which will handle the requests to the RSS Feed nodes (note that I changed the alias of ‘RSS Feed’ doc type to ‘RssFeed’ rather than the default ‘RSSFeed’).

Note that the pages I will use for the RSS feed have a title and description property, which I use for the RSS content.

public class RssFeedController : RenderMvcController
{
    public override ActionResult Index(RenderModel model)
    {
        int rssFeedContentRootId = model.Content.GetPropertyValue<int>("contentRoot");
        if (rssFeedContentRootId > 0)
        {
            IPublishedContent rssFeedContentRoot = Umbraco.Content(rssFeedContentRootId);
            IEnumerable<SyndicationItem> rssFeed = rssFeedContentRoot
                 .Children.Select(x => new SyndicationItem(
                     x.GetPropertyValue<string>("title"),
                     x.GetPropertyValue<string>("description"),
                     new Uri(x.UrlWithDomain()),
                     x.Id.ToString(CultureInfo.InvariantCulture),
                     x.UpdateDate));

            return new SyndicationFeedResult(model.Content.GetPropertyValue<string>("feedTitle"), rssFeed);
        }

        return HttpNotFound();
    }
}

The Custom ‘SyndicationFeedResult’

Create a custom action result, which will render the contents for our RSS feed.

Note that you will need to add a reference to System.ServiceModel.

public class SyndicationFeedResult : FileResult
{
    private readonly SyndicationFeed _feed;

    public SyndicationFeedResult(string title, IEnumerable<SyndicationItem> feedItems)
        : base("application/rss+xml")
    {
        _feed = new SyndicationFeed(title, String.Empty, HttpContext.Current.Request.Url, feedItems);
    }

    protected override void WriteFile(HttpResponseBase response)
    {
        using (XmlWriter writter = XmlWriter.Create(response.OutputStream))
        {
            _feed.GetRss20Formatter().WriteTo(writter);
        }
    }
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *