Domanda

Ho questo pezzo di codice:

    var settings = WebConfigurationManager.AppSettings;
    var consumerKey = settings["Twitter.ConsumerKey"];
    var consumerSecret = settings["Twitter.ConsumerSecret"];
    var authToken = settings["Twitter.OAuthToken"];
    var authVerifier = settings["Twitter.OAuthVerifier"];

    //var accessToken = GetAccessToken(
    //    consumerKey, consumerSecret, authToken, string.Empty);

    var tokens = new OAuthTokens()
    {
        AccessToken = authToken,
        AccessTokenSecret = authVerifier,
        ConsumerKey = consumerKey,
        ConsumerSecret = consumerSecret
    };

    TwitterStatus.Update(tokens, txtComment.Text);

Tutto ciò di cui ho bisogno è aggiornare il mio stato su Twitter.Purtroppo non funziona.Ha funzionato solo una volta quando ho effettuato l'accesso a Twitter per concedere l'accesso all'applicazione.Ho quindi archiviato authToken e authVerifier in modo da poterli riutilizzare per aggiornamenti futuri.

Qualche idea su cosa sia sbagliato?

AGGIORNAMENTO: Ho appena cambiato il codice in:

        TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, txtComment.Text);
    if (tweetResponse.Result == RequestResult.Success)
        lblMessage.Text = "Twitter status successfully posted.";
    else
        lblMessage.Text = string.Format("Twitter status update failed with Error: '{0}'",
            tweetResponse.ErrorMessage);

e ricevo un messaggio di errore: "Token non valido/scaduto".

È stato utile?

Soluzione

si memorizzano i valori errati. I valori authtoken e della verifica devono essere rapidamente sostituita con un token di accesso utilizzando OAuthUtility.GetAccessToken (...). Il token di accesso che è tornato da quel metodo è quello che dovrebbe essere conservato e alimentato Twitterizer.

-Ricky
Il Twitterizer Autore

Altri suggerimenti

Volevo poter effettuare un semplice aggiornamento dello stato da C#/.NET, ma non volevo incorporare una libreria di grandi dimensioni.

Quindi ho scritto un piccolo Classe OAuth.Manager quello fa queste cose.

È descritto qui:
OAuth con verifica in .NET

Codice di esempio per aggiornare lo stato:

var oauth = new OAuth.Manager(); 
oauth["consumer_key"] = CONSUMER_KEY; 
oauth["consumer_secret"] = CONSUMER_SECRET; 
oauth["token"] = your_stored_access_token; 
oauth["token_secret"] = your_stored_access_secret; 
var url = "http://api.twitter.com/1/statuses/update.xml?status=Hello+World";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST"); 

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode != HttpStatusCode.OK)
        MessageBox.Show("There's been a problem trying to tweet:" +
                        Environment.NewLine +
                        response.StatusDescription +
                        Environment.NewLine +
                        Environment.NewLine +
                        "You will have to tweet manually." +
                        Environment.NewLine);
}

Per la prima volta è necessario ottenere un token di accesso e un segreto.Questo viene fatto in un processo in più fasi, a partire da questo codice:

var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET;
oauth.AcquireRequestToken("https://api.twitter.com/oauth/request_token", "POST"); 

Il passaggio 2 consiste nel dire all'utente** di visitare https://api.twitter.com/oauth/authorize?oauth_token=XXXX dove xxxx viene sostituito con l'effettivo token ricevuto, accessibile in questo caso da oauth["token"].Il passaggio 3 consiste nel dire all'utente di prendere (ctrl-c) il PIN dalla pagina Web e incollarlo nella tua app, dove utilizzerai il pin per ottenere un altro tipo di token.

Un modo migliore consiste nell'automatizzare la sequenza dell'interfaccia utente Web utilizzando un Windows Form con un controllo WebBrowser incorporato.Quando imposti la proprietà Url di quel controllo sul valore appropriato, mostrerà quella pagina web per te, all'interno del modulo principale della tua app.Puoi anche automatizzare la parte in cui recuperi il PIN.Ciò riduce i cambi di contesto per l'utente e rende le cose più semplici da comprendere.

Ad ogni modo, con il pin che fai, passaggio 4:

oauth.AcquireAccessToken("https://api.twitter.com/oauth/access_token",
    "POST",
    pin); 

...che invia un'altra richiesta HTTP REST e quando ritorna avrai un token di accesso e un segreto, disponibili in oauth["token"] E oauth["token_secret"].

Questa operazione di autorizzazione con l'interfaccia utente Web deve avvenire solo una volta;dopo aver ottenuto il token di accesso e il segreto una volta, puoi conservarli e riutilizzarli.Non scadono mai, dice Twitter.

È quindi possibile procedere all'invio dell'aggiornamento dello stato...

var url = "http://api.twitter.com/1/statuses/update.xml?status=Hello+World";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST"); 
...

...come sopra.

Lo so, sono in ritardo al gioco, ma ho creato un video tutorial end-to-end che mostra esattamente come fare questo: creo un'applicazione su dev.twitter.com, installo twitterizer utilizzando NuGet, scrivere il codice per gestire l'OAuth e, infine, scrivere il codice per utilizzare il token di accesso ricevuti da Twitter per fare un tweet.

Video: http://www.youtube.com/watch?v=TGEA1sgMMqU

Esercitazione: http: // www. markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet

Codice (nel caso in cui non si wan di lasciare questa pagina):

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

using Twitterizer;

namespace PostFansTwitter
{
    public partial class twconnect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var oauth_consumer_key = "YOUR_CONSUMER_KEY_HERE";
            var oauth_consumer_secret = "YOUR_CONSUMER_SECRET_KEY_HERE";

            if (Request["oauth_token"] == null)
            {
                OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
                    oauth_consumer_key,
                    oauth_consumer_secret,
                    Request.Url.AbsoluteUri);

                Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
                    reqToken.Token));
            }
            else
            {
                string requestToken = Request["oauth_token"].ToString();
                string pin = Request["oauth_verifier"].ToString();

                var tokens = OAuthUtility.GetAccessToken(
                    oauth_consumer_key,
                    oauth_consumer_secret,
                    requestToken,
                    pin);

                OAuthTokens accesstoken = new OAuthTokens()
                {
                    AccessToken = tokens.Token,
                    AccessTokenSecret = tokens.TokenSecret,
                    ConsumerKey = oauth_consumer_key,
                    ConsumerSecret = oauth_consumer_secret
                };

                TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
                    accesstoken,
                    "Testing!! It works (hopefully).");

                if (response.Result == RequestResult.Success)
                {
                    Response.Write("we did it!");
                }
                else
                {
                    Response.Write("it's all bad.");
                }
            }
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top