Warning: Invalid argument supplied for foreach() in D:\home\site\wwwroot\wp-includes\translations.php on line 1174 Warning: Invalid argument supplied for foreach() in D:\home\site\wwwroot\wp-includes\translations.php on line 1367

RSS is something quite standard, and as such, is easy to read and create.

We start off with a FeedResult class, which inherits from ActionResult

using System;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace Data.Controllers
{
    public class FeedResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }

        private readonly SyndicationFeedFormatter feed;
        public SyndicationFeedFormatter Feed{
            get { return feed; }
        }

        public FeedResult(SyndicationFeedFormatter feed) {
            this.feed = feed;
        }

        public override void ExecuteResult(ControllerContext context) {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? 
                ContentType : "application/rss+xml";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (feed != null)
                using (var xmlWriter = new XmlTextWriter(response.Output)) {
                    xmlWriter.Formatting = Formatting.Indented;
                    feed.WriteTo(xmlWriter);
                }
        }
    }
}

 

And finally, we create a Controller Method to create the RSS

public ActionResult MyRss()
{
    var postItems = new List();
    using (Repository rep = new Repository())
    {
        var list = rep.GetData();

        if (list != null && list.Count() > 0)
        {
            var itemList = list.Take(20);

            foreach (var item in itemList)
            {
                postItems.Add(
                    new SyndicationItem(
                        item.Title, //a Title for the RSS Item
                        item.Description, //a short description for the Item
                        new Uri("http://example.com/" + item.Link) //a link to this item
                    )
                );
            }
        }
    }

    var feed = new SyndicationFeed("My Site Name", "", new Uri("http://example.com/"), postItems)
    {
        Copyright = new TextSyndicationContent("Copyright " + DateTime.Now.Year + " My Site", 
                        TextSyndicationContentKind.Plaintext),
        Language = "en-US"
    };

    return new FeedResult(new Rss20FeedFormatter(feed));
}