Kobarin's Development Blog

C#やASP.NETなどについての記録です。

ASP.NETでTwitterのOauthを使う

1. まずTwitterアプリケーションを登録
http://twitter.com/apps

2. 「consumer key」と「consumer secret」を取得

3. ASP.NETサイトを開く

4. web.configを開き、<appSettings>に以下のように記述。「・・・」には、それぞれのキーを記入。


  
  

5. 以下ページにある「Download the full code here」よりZIPをダウンロードし解凍後、
  「oAuth.cs」「oAuthTwitter.cs」の2クラスファイルを、AppCodeフォルダに設置
http://www.voiceoftech.com/swhitley/?p=681

6. 以下のASPXファイルを設置

protected void Page_Load(object sender, EventArgs e) {
  string url = "";
  string xml = "";
  oAuthTwitter oAuth = new oAuthTwitter();

  if (Request["oauth_token"] == null) {
    //Redirect the user to Twitter for authorization.
    //Using oauth_callback for local testing.
    oAuth.CallBackUrl = "http://localhost/";
    Response.Redirect(oAuth.AuthorizationLinkGet());
  }
  else
  {
    //Get the access token and secret.
    oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
    if (oAuth.TokenSecret.Length > 0) {
      //We now have the credentials, so make a call to the Twitter API.
      url = "http://twitter.com/account/verify_credentials.xml";
      xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
      Label1.InnerHtml = Server.HtmlEncode(xml);

      //POST Test
      //url = "http://twitter.com/statuses/update.xml";
      //xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("Hello @swhitley - Testing the .NET oAuth API"));
      Label1.InnerHtml = Server.HtmlEncode(xml);
    }
  }
}