Tutorial: Using Twitter OAuth and the Twitter API with ASP.NET and C#

Post to Twitter

There is a dead simple way in .NET to use the Twitter API including authenticating your application against OAuth. The library I’ll be using today is called TwitterVB. Don’t let the name fool you though because you can use this in any .NET language and today I’ll be using C# with ASP.NET.

Things you need for this tutorial:
1. Visual Studio 2010 (Visual Studio Express should be fine) with ASP.NET working. (Visual Studio 2008 should work as well but I didn’t test that)
2. TwitterVB library, download this and extract the assembly somewhere. (I used the Nov. 29 beta version)
3. This probably goes without saying but you need to have a Twitter account
4. You need to register a Twitter app in order to get a consumer key and consumer secret key: http://dev.twitter.com/apps/new

Note: My code is adapted from the TwitterVB documentation. My personal thanks to the TwitterVB team and their excellent and well documented library.

Start Visual Studio 2010 and create a new empty ASP.NET Web Application called NetTwitter:

Note: This would work just as well with ASP.NET MVC.

Once the project has been created right-click on NetTwitter in the Solution Explorer and add a new WebForm called default.aspx:

Right-click on the references in the Solution Explorer and add the reference to the TwitterVB.dll you downloaded and extracted earlier:

Since the code is short and easy I’ll just paste the contents of my file here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TwitterVB2;
using System.Diagnostics;

namespace NetTwitter
	public partial class _default : System.Web.UI.Page
		private String ConsumerKey = "CONSUMERKEY";
		private String ConsumerKeySecret = "CONSUMERKEYSECRET";

		protected void Page_Load(object sender, EventArgs e)
			TwitterAPI twitterAPI = new TwitterAPI();

			if (String.IsNullOrEmpty(Request["oauth_token"]))
				// Send the browser to Twitter for authentication along with a callback URL
				Response.Redirect(twitterAPI.GetAuthorizationLink(ConsumerKey, ConsumerKeySecret, "http://localhost:1686/default.aspx"));
				// Exchange the request token for an access token
				twitterAPI.GetAccessTokens(ConsumerKey, ConsumerKeySecret, Request["oauth_token"], Request["oauth_verifier"]);
				// You've got all the tokens now.  You can write them to a database, cookies, or whatever

				twitterAPI.AuthenticateWith(ConsumerKey,ConsumerKeySecret,twitterAPI.OAuth_Token,twitterAPI.OAuth_TokenSecret) ;
				// Get some tweets from their timeline
				foreach(TwitterStatus tweet in twitterAPI.HomeTimeline())
					Response.Write("<strong>" + tweet.User.ScreenName + ":</strong>" + tweet.Text + "<br />");

A few things to note:
1. Make sure you modify the callback address to whatever your using.
2. When you’ve registered your Twitter app fill in the ConsumerKey and ConsumerKeySecret variables.

The callback URL you pass back is what Twitter will return. In my case since I am debugging on my local machine I simply passed back a localhost address. In a production or test environment you would pass back the actual server address your app is hosted on.

Run the project and you will be redirected to a page similar to this:

Use your Twitter account to login and click the Allow button.

The results:

You can see how easy this is to use. Go ahead and play around with the TwitterVB API. You can send direct messages and updates as simple as:

// Post an update
twitterAPI.Update("Hello from .NET!")
// Send a direct message
twitterAPI.SendDirectMessage("chadlung", "Hi!")

Just make sure you don’t go over 140 characters with your updates and ensure you’ve called AuthenticateWith prior to running a TwitterVB API call just like in the ASP.NET WebForm example I did above.

Post to Twitter

This entry was posted in ASP.NET, C#. Bookmark the permalink.

11 Responses to Tutorial: Using Twitter OAuth and the Twitter API with ASP.NET and C#

  1. Adam Green says:

    This is a super simple tutorial for Twitter OAuth and C#. If your readers also want the same type of treatment for programming the Twitter API with PHP and OAuth, this tutorial might be useful:

  2. dani spain says:

    simple and very usefull for beginers!
    thanks & congratulations

  3. Neha says:

    This code proved to be very useful for solving my problem…one thing i just wished to inquire that whether we can make this consumer key and secret as dynamic variables i.e to take value at runtime… rather than passing it as a value

  4. Nitin says:

    It ask for twitter Login/password every time I run my application.
    Is there any way to avoid this?


  5. Djeebay says:

    I have an error in VS 2010 on the page default.aspx when i’m debugging, I followed your tutorial.
    My error is this one:

    Parser Error
    Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

    Parser Error Message: ‘netTwitter._default’ is not allowed here because it does not extend class ‘System.Web.UI.Page’.

    Source Error:
    (the error is apparently the first line)
    Line 1:
    Line 2:
    Line 3:

    Is there something i missed ?
    Sorry but i’m a begginer in development.
    If someone can help me, thanks a lot…


  6. Dhrup vishwakarma says:

    thank yaar you solved my problem

  7. Nani says:

    I am getting the below error:

    Response.Redirect(twitterAPI.GetAuthorizationLink(ConsumerKey, ConsumerKeySecret,Request.Url.ToString()));

    Error : Desktop applications only support the oauth_callback value ‘oob’

    Can you please let me know,how we can resolve this issue.


  8. Pingback: Tutorial: Using Twitter OAuth and the Twitter API with ASP.NET and C# | Giant Flying Saucer - Mustafa Kipergil - Mustafa Kipergil

  9. Amir says:

    I have same Nani’s problem, please help about it.

  10. tarun says:

    Hey, thanks for the tutorial, it works great 🙂

    You’ve put it really well.

    I have a doubt though, Once I get the Authorization done, Twitter asks me to enter a PIN for my app, where does that go?


Comments are closed.