Get latest tweets with C# using OAuth and Twitter API v1.1

19 July 2013

Recently Twitter retired their v1 API, putting an end to any unauthenticed access to twitter data. The new v1.1 API requires all requests to be authenticated using OAuth.

This caused alot of twitter "latest tweets" feeds to stop working, including a few on websites that I'd setup some time ago using the blogger.js (http://twitter.com/javascripts/blogger.js) script.

So if you have a ASP.NET site that's using the deprecated blogger.js script or has a latest tweets widget that's stopped working, here's how you can fix it in C# and ASP.NET.

The first thing you need to do is create a twitter app at https://dev.twitter.com/apps, this will give you the bits you need to authenticate to twitter using OAuth, namely:

  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret

Open your ASP.NET project in visual studio and install the LINQ to Twitter package from NuGet, either by right clicking the project and clicking Manage NuGet Packages or by running the following command in the Package Manager Console:

Install-Package linqtotwitter

Then use the following C# code to retrieve the latest three tweets from your twitter account:

var auth = new SingleUserAuthorizer
{
    Credentials = new InMemoryCredentials
    {
        ConsumerKey = "[consumer key from twitter app]",
        ConsumerSecret = "[consumer secret from twitter app]",
        OAuthToken = "[access token from twitter app]",
        AccessToken = "[access token secret from twitter app]"
    }
};

var twitterCtx = new TwitterContext(auth);

var tweets =
    (from tweet in twitterCtx.Status
    where tweet.Type == StatusType.User
            && tweet.ScreenName == "[your screen name]"
    select tweet).Take(3);