Twitter RSS Feed Reader in MVC 4

In this blog post you will learn how to setup the Twitter RSS Feed Reader in MVC 4. I’m using the same technique I used in my last post to read the Facebook feeds. Let’s look at the image that we will be creating using the given code.


At very first, setup the model like this:

    public class TwitterRSS
    {
        public string Title { get; set; }
        public string Link { get; set; }
        public string PubDate { get; set; }
    }

    public class TwitterRssReader
    {
        public static IEnumerable<TwitterRSS> GetFeed()
        {
            var client = new WebClient();
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            var xmlData = client.DownloadString("https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=itorian");

            XDocument xml = XDocument.Parse(xmlData);

            var TwitterUpdates = (from story in xml.Descendants("item")
                                select new TwitterRSS
                                {
                                    Title = ((string)story.Element("title")),
                                    Link = ((string)story.Element("link")),
                                    PubDate = ((string)story.Element("pubDate"))
                                }).Take(10);

            return TwitterUpdates;
        }
    }

You need to change the above download string url or just replace your twitter handler name or screen name.

Now, let me show you the twitter RSS page that we tried to target in above code:


Now, setup the controller like this:

        public ActionResult Index()
        {
            ViewBag.TwitterFeed = RSS_Reader.Models.TwitterRssReader.GetFeed();
            return View();
        }

Next, use following view page:

<table>
<tr>
    <th>
        <h3>Twitter Updates</h3>
    </th>
</tr>

@foreach (var item in ViewBag.TwitterFeed)
{
<tr>
    <td>
        @item.Title <a href="@item.Link" target="_blank"> more </a> on @Convert.ToDateTime(item.PubDate)
    </td>
</tr>
}
</table>

Now, you all set, run the application.

Hope this helps. Thanks.

Comments

  1. This is not scalable. If you have your twitter feed on a footer e.g then you would need to call the Twitter Feed in the controller action for each page.

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System