Published on: 10 August, 2013

How to post message to twitter in ASP.Net C#

Posted by andy | 8713 views 2 likes 1 favourites 11 comments
Tumblr Digg Google Plus

As we know version 1.0 of Twitter API has been discontinued and many programmers may find it quite troublesome to post message in twitter. In this tutorial, we will guide you step by step on how to post message to Twitter account using oauth method.

First of all, in order to post message to Twitter, we have to create a Twitter app in order to get required access tokens. You will need to visit this site https://dev.twitter.com.

If you do not have a Twitter account, you will need to register. Once register, you can follow up the following images.

Twitter Dev homepage

Twitter My Applications page

Twitter Application Form

Once created, you will see the following application overview as shown below. We need to create the access token and change the permission level in order to make it work otherwise you will get 401 unauthorized oauth response. Firstly click the Create My Access Token button. This will create the access token at the Read Only permission level.

Twitter Application Overview

Once the access token is created, we need to adjust the permission level by going to the settings tab.

Twitter Application Settings

Please choose the access option: Read, Write and Access direct messages. Once selected, click the update button.

Twitter Permission Level

Once updated, you will notice the token access details will say the application will now have read, write and access direct messages level.

Twitter Access Tokens

Now we are ready with the coding to post our message in ASP.Net C#.

//Remember to import the following namespaces
using System.Net;
using System.IO;
using System.Security.Cryptography;

//function to post message to twitter (parameter string message)
        private static void PostMessageToTwitter(string message)
        {
            //The facebook json url to update the status
            string twitterURL = "https://api.twitter.com/1.1/statuses/update.json";

            //set the access tokens (REQUIRED)
            string oauth_consumer_key = "Enter your customer key";
            string oauth_consumer_secret = "Enter your customer secret";
            string oauth_token = "Enter your access token";
            string oauth_token_secret = "Enter your access token secret";

            // set the oauth version and signature method
            string oauth_version = "1.0";
            string oauth_signature_method = "HMAC-SHA1";

            // create unique request details
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            System.TimeSpan timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            // create oauth signature
            string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";

            string baseString = string.Format(
                baseFormat,
                oauth_consumer_key,
                oauth_nonce,
                oauth_signature_method,
                oauth_timestamp, oauth_token,
                oauth_version,
                Uri.EscapeDataString(message)
            );

            string oauth_signature = null;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(Uri.EscapeDataString(oauth_consumer_secret) + "&" + Uri.EscapeDataString(oauth_token_secret))))
            {
                oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes("POST&" + Uri.EscapeDataString(twitterURL) + "&" + Uri.EscapeDataString(baseString))));
            }

            // create the request header
            string authorizationFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " + "oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " + "oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " + "oauth_version=\"{6}\"";

            string authorizationHeader = string.Format(
                authorizationFormat,
                Uri.EscapeDataString(oauth_consumer_key),
                Uri.EscapeDataString(oauth_nonce),
                Uri.EscapeDataString(oauth_signature),
                Uri.EscapeDataString(oauth_signature_method),
                Uri.EscapeDataString(oauth_timestamp),
                Uri.EscapeDataString(oauth_token),
                Uri.EscapeDataString(oauth_version)
            );

            HttpWebRequest objHttpWebRequest = (HttpWebRequest)WebRequest.Create(twitterURL);
            objHttpWebRequest.Headers.Add("Authorization", authorizationHeader);
            objHttpWebRequest.Method = "POST";
            objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            using (Stream objStream = objHttpWebRequest.GetRequestStream())
            {
                byte[] content = ASCIIEncoding.ASCII.GetBytes("status=" + Uri.EscapeDataString(message));
                objStream.Write(content, 0, content.Length);
            }

            var responseResult = "";
            try
            {
                //success posting
                WebResponse objWebResponse = objHttpWebRequest.GetResponse();
                StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
                responseResult = objStreamReader.ReadToEnd().ToString();
            }
            catch (Exception ex)
            {
                //throw exception error
                responseResult = "Twitter Post Error: " + ex.Message.ToString() + ", authHeader: " + authorizationHeader;
            }
        }
}

You may want to check out our other article about posting message to facebook. Click this article How to post message to facebook in ASP.Net C#.

Comments
Mohammad Amer
Commented on: 12 May, 2016 05:59:22 AM
Get Error The remote server returned an error: (403) Forbidden.
andy
Commented on: 07 Feb, 2017 03:53:06 PM
Hi Mohammad, I have fixed the issue with the posting message problem. The only thing you need to change is the url. Twitter had requires https instead of http. So the new url will be: https://api.twitter.com/1.1/statuses/update.json
Thomas
Commented on: 29 Dec, 2016 01:24:54 AM
i'm also get same error. any one please guide me to post tweet with link..
andy
Commented on: 07 Feb, 2017 03:53:35 PM
Hi Thomas, I have fixed the issue with the posting message problem. The only thing you need to change is the url. Twitter required https instead of http. So the new url will be: https://api.twitter.com/1.1/statuses/update.json
andy
Commented on: 07 Feb, 2017 03:53:49 PM
Hi Leiner, I have fixed the issue with the posting message problem. The only thing you need to change is the url. Twitter had requires https instead of http. So the new url will be: https://api.twitter.com/1.1/statuses/update.json
leiner Ledezma
Commented on: 06 Feb, 2017 06:40:33 AM
Exception: the remote server an error 403 forbidden
Christopher Lee
Commented on: 16 Feb, 2017 12:22:59 PM
Hello Andy, Thanks for this, worked perfectly. How do I add an image to it?
andy
Commented on: 20 Feb, 2017 10:02:40 AM
Hi Christoper, Please see the following link. https://twittercommunity.com/t/uploading-media-in-c/37908/5 The codes are quite similar with the one I have, to test it, just paste your customer and access token keys and modify the path of the image. The easy path to test maybe something like this: c:\\sampleimage.jpg
andy
Commented on: 23 May, 2017 09:07:46 AM
Would you be able to catch the error? and see what is the error exception to know further what's went wrong?
Vishal Joshi
Commented on: 22 May, 2017 09:04:19 PM
Hello, First time i Post on twitter its successfully done but when i doing same process again that time i got 403 error. So can you tell me how to short this error.
Atik
Commented on: 12 Aug, 2017 09:56:00 PM
Thanks For the Code, it's really simple and helpful. Thank again.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Related Articles
Published on: 13 February, 2017
One thing to remember when publishing your ASP.Net web applications, you may find out, some files could be not completely published due to the settings on the file properties. One example that I had are some font types file. In order to fix this problem you can navigate to the files that are missing and right click the properties.
Published on: 11 May, 2016
The slidingExpiration attribute is used in ASP.Net form authentication. This property is used to reset the expiration time for a valid authentication cookie if a request that has already being made has passed the timeout interval. Which means, if it is already expires, the current user will require to re-authentication again.
Related Tutorials