2016-10-04 46 views
0

我在asp.net中有一個web應用程序。我想用twiiter登錄來獲取用戶信息。我按照下面的文章使用twitter登錄以獲取用戶簡介asp.net

http://www.aspsnippets.com/Articles/Login-with-Twitter-in-ASPNet-using-Twitter-Button.aspx

我被重定向到Twitter的應用程序,然後在身份驗證之後,我被重定向到我的本地應用程序中提到的所有指令。然後我檢查用戶是否授權,但是當我嘗試通過方法獲取用戶詳細信息時FetchProfile()我收到錯誤消息。

我的代碼如下:

首先按鈕點擊

protected void LoginTwitter(object sender, EventArgs e) 
{ 

    if (!TwitterConnect.IsAuthorized) 
    { 
     TwitterConnect twitter = new TwitterConnect(); 
     twitter.Authorize(Request.Url.AbsoluteUri.Split('?')[0]); 
    } 

} 

然後從Twitter認證後回來。應用 的頁面加載我檢查URL及其

http://localhost:63977/Account/Login?oauth_token=K0mECAAAAAAAxRXEAAABV44xPgc&oauth_verifier=qYLFiOlFPx4gxEu6V4AmTJG2JNjJ3nV2 

然後代碼檢查

protected void Page_Load(object sender, EventArgs e) 
{ 
    TwitterConnect.API_Key = HelperClasses.TwitterApiKey; 
    TwitterConnect.API_Secret = HelperClasses.TwitterApiSecret; 

    if (Request.QueryString["oauth_token"] != null) 
    { 
     //twiiter 
     if (TwitterConnect.IsAuthorized) 
     { 
      TwitterConnect twitter = new TwitterConnect(); 
      //LoggedIn User Twitter Profile Details 
      DataTable twitterUserDataTable = twitter.FetchProfile(); // error here 
     } 
    } 
} 

回答

1

Tweetinvi提供了一個樣本項目究竟做你想做的事:https://github.com/linvi/tweetinvi/tree/master/Examplinvi.Web

我強調的線條,你會感興趣的:

https://github.com/linvi/tweetinvi/blob/master/Examplinvi.Web/Controllers/HomeController.cs#L14-L36

您也可以在這裏tweetinvi更多關於身份驗證:https://github.com/linvi/tweetinvi/wiki/Authentication

這裏是您要使用ASP.NET驗證的片段:

private IAuthenticationContext _authenticationContext; 

// Step 1 : Redirect user to go on Twitter.com to authenticate 
public ActionResult TwitterAuth() 
{ 
    var appCreds = new ConsumerCredentials("CONSUMER_KEY", "CONSUMER_SECRET"); 

    // Specify the url you want the user to be redirected to 
    var redirectURL = "http://" + Request.Url.Authority + "/Home/ValidateTwitterAuth"; 
    _authenticationContext = AuthFlow.InitAuthentication(appCreds, redirectURL); 

    return new RedirectResult(authenticationContext.AuthorizationURL); 
} 

public ActionResult ValidateTwitterAuth() 
{ 
    // Get some information back from the URL 
    var verifierCode = Request.Params.Get("oauth_verifier"); 

    // Create the user credentials 
    var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, _authenticationContext); 

    // Do whatever you want with the user now! 
    ViewBag.User = Tweetinvi.User.GetAuthenticatedUser(userCreds); 
    return View(); 
}