Creating RSS feed in ASP.net mvc3

//Creating RSS feed in ASP.net mvc3

Creating RSS feed in ASP.net mvc3

By |2012-10-22T14:32:44+00:00October 22nd, 2012|Categories: Programming|0 Comments

In this toturial we are going through steps to create rss feed from a list of items using .NET’s built in SyndicatedFeed and SyndicatedItem class for content and two classes (Rss20FeedFormatter and Atom10FeedFormatter )  to handle XML generation with correct encoding, formatting and optional fields.

  1. Create an empty mvc3 application and name it “RSSFeed.Website” then add Home controller.
  2. Create a class and name it NewsItem  this class we will be used as a model for retrieving feed data from the database “i will fill it manually in a the next step ”
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace RSSFeed.Website.Models
    {
        public class NewsItem
        {
            public string Title { get; set; }
            public string Body { get; set; }
            public string ImageUrl { get; set; }
            public string Author { get; set; }
            public DateTime PublishedDate { get; set; }
            public string Url { get; set; }
        }
    }
  3. Optional step, Fill in NewsItem list if you have items in database so there is no need to fill the list like that you can get the data from the database and return it in a list of items
    public class NewsManager
        {
            public List<NewsItem> GenerateNews()
            {
                List<NewsItem> newsItems = new List<NewsItem>();
    
                NewsItem newsItem1 = new NewsItem()
                {
                    Author = "Mohamed Salah",
                    Body = "Clashes have broken out in several areas of Lebanon following Sunday's funeral of the senior intelligence official, Wissam al-Hassan.The most serious confrontations were in the northern city of Tripoli, where at least three people were killed as Sunni and Shia gunmen exchanged fire.In Beirut, there were clashes between soldiers and armed men in the Sunni Tariq al-Jadida district.Gen Hassan, a Sunni, was killed by a car bomb in the capital on Friday.He was the head of the intelligence branch of the Internal Security Forces and an outspoken critic of Syrian President Bashar al-Assad, a member of the Shia-based Alawite sect.",
                    Title = "Lebanon sees sectarian clashes after Hassan killing",
                    PublishedDate = DateTime.Today.AddDays(-5),
                    ImageUrl = "http://news.bbcimg.co.uk/media/images/63629000/jpg/_63629530_tripoli_reuters.jpg",
                    Url = "http://www.bbc.co.uk/news/world-middle-east-20025095"
                };
                newsItems.Add(newsItem1);
    
                NewsItem newsItem2 = new NewsItem()
                {
                    Author = "Mohamed Salah",
                    Body = "Cuba's revolutionary former leader Fidel Castro has written a strongly-worded article condemning persistent rumours that he is on his death bed.The 86-year-old attacked international media \"lies\", and published photos of himself in Cuba's state media.He said he was in good health, and could not even remember the last time he had a headache.Venezuelan politician Elias Jaua said on Sunday he had a five-hour meeting with Mr Castro the previous day.He presented a photo of the encounter, and said the former Cuban leader was \"very well, very lucid\".",
                    Title = "Cuba's Fidel Castro attacks 'lies' about his health",
                    PublishedDate = DateTime.Today.AddDays(-4),
                    ImageUrl = "http://news.bbcimg.co.uk/media/images/63628000/jpg/_63628162_63628161.jpg",
                    Url = "http://www.bbc.co.uk/news/world-latin-america-20025624"
                };
                newsItems.Add(newsItem2);
    
                return newsItems;
            }
        }
  4. We have to build our FeedResult class
    using System;
    using System.ServiceModel.Syndication;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;
    using System.Xml;
    
    namespace RSSFeed.Website.Models
    {
        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);
                    }
            }
        }
    }
  5. We almost done we have to create our rss page so we are going to create an ActionResult called NewsRss in HomeController
    public ActionResult NewsRss()
            {
                NewsManager newsManager = new NewsManager ();
                var postItems = newsManager.GenerateNews().OrderBy(p => p.PublishedDate).Take(25)
                    .Select(p => new SyndicationItem(p.Title, p.Body, new Uri(p.Url)));
    
                var feed = new SyndicationFeed("New Title", "New Description", new Uri("http://www.yahoo.com"), postItems)
                {
                    Copyright = new TextSyndicationContent("© 2010 copyrights reserved"),
                    Language = "en-US"
                };
    
                return new FeedResult(new Rss20FeedFormatter(feed));
            }
  6. we are done now except just putting a link to home to open up our RSS
    @Html.ActionLink("RSS", "NewsRss", "Home", null, new { target = "_blank" })

You can download a sample from here

 

About the Author:

Leave A Comment