Send Direct message from C# web application getting Unauthorized 401 error

oauth
rest
api

#1

My Code ASP.net C# :


public void SendDirectMessage(string resource_url, string ScreenName, string Msg)
    {
        // oauth application keys
        //Using API getting secret in token and token in secret
        var oauth_token = Convert.ToString(ViewState["Accesstoken"]); //"622979601-fB61G2YL49PQPKnN8u0sirUwscggUUS5x7Ly7urG";
        var oauth_token_secret = Convert.ToString(ViewState["AccesstokenSecret"]);  //"ZYlYneKW1FQt7cNuJc7PgRhjfG2yp7Og1AgvQC70kuHam";
        var oauth_consumer_key = ConsumerKey;
        var oauth_consumer_secret = ConsumerSecret;

        // oauth implementation details
        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";

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


        // create oauth signature
        var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                        //"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}&screen_name={7}";//&result_type=mixed&count=4
                        "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";

        var baseString = string.Format(baseFormat,
                                    oauth_consumer_key,
                                    oauth_nonce,
                                    oauth_signature_method,
                                    oauth_timestamp,
                                    oauth_token,
                                    oauth_version
                                    //Uri.EscapeDataString(Msg),
                                    //,Uri.EscapeDataString(ScreenName)
                                    );

        baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

        var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                "&", Uri.EscapeDataString(oauth_token_secret));

        string oauth_signature;
        using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
        {
            oauth_signature = Convert.ToBase64String(
                hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
        }

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

        var authHeader = string.Format(headerFormat,
                                Uri.EscapeDataString(oauth_nonce),
                                Uri.EscapeDataString(oauth_signature_method),
                                Uri.EscapeDataString(oauth_timestamp),
                                Uri.EscapeDataString(oauth_consumer_key),
                                Uri.EscapeDataString(oauth_token),
                                Uri.EscapeDataString(oauth_signature),
                                Uri.EscapeDataString(oauth_version)
                        );


        ServicePointManager.Expect100Continue = false;

        // make the request
        //var postBody = "?text" + Uri.EscapeDataString(Msg);// +"&result_type=mixed&count=4";// +"&count=100";//
        var postBody = "?text" + Uri.EscapeDataString(Msg) + "&screen_name=" + Uri.EscapeDataString(ScreenName);// +"&result_type=mixed&count=4";// +"&count=100";//
        resource_url += postBody;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
    
            var response = (HttpWebResponse)request.GetResponse();
            var reader = new StreamReader(response.GetResponseStream());
            var objText = reader.ReadToEnd();
     
    }

I don’t know what i am doing wrong. But, I am getting 401 Unauthorized error in response.

Thanks!


#2

Same Issue I am facing if i use screen_name other then user_id. With user_id it work fine. Any help will be appreciated


#3

your baseString is incomplete. It should be :

var baseFormat = “oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}” +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}&text={7}";

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