检索userId并使用linqtotwitter发送私人消息

时间:2012-10-24 13:47:09

标签: asp.net-mvc-3 linq-to-twitter

我想在asp.net mvc3中使用我的网络应用程序向Twitter发送私信。我正在使用oauth进行授权,这是我的代码:

在AccountController中

     public ActionResult LogOn()
    {
        credentials.ConsumerKey = TwitterClient.ConsumerKey;
        credentials.ConsumerSecret = TwitterClient.ConsumerSecret;

        auth = new MvcAuthorizer {  Credentials = credentials };
        auth.CompleteAuthorization(Request.Url);
        if (!auth.IsAuthorized)
        {
            string callbackUrl = "http://127.0.0.1:31891/Account/CompleteAuth";
            Uri uri = new Uri(callbackUrl);
            return auth.BeginAuthorization(uri);
        }
        return RedirectToAction("Index", "Home");
     }

用户获得授权后,他会重定向到操作CompleteAuth,我会获得令牌tokenSecret,此处是此操作的代码:

    public ActionResult CompleteAuth(string oauth_token, string oauth_verifier)
   {          
        string AccessToken = oauth_token;
        string AccessTokenSecret = oauth_verifier;
        TempData["AccessToken"] = AccessToken;
        TempData["TokenSecret"] = AccessTokenSecret;
        return RedirectToAction("Tweeting","Home");
    }

之后,它会重定向到Home in action Tweeting,当我尝试获取userId并向他发送直接消息时:

    public ActionResult Tweeting()
    {
        var auth = new MvcAuthorizer
        {
            Credentials = new InMemoryCredentials()
            {
                ConsumerKey  = TwitterClient.ConsumerKey,
                ConsumerSecret = TwitterClient.ConsumerSecret,
                //OAuthToken = (string)Session["AccessToken"],
                //AccessToken = Session["TokenSecret"]
                OAuthToken = TempData["AccessToken"] as string,
                AccessToken = TempData["TokenSecret"] as string
            }
        };
        var twitterContext = new TwitterContext(auth);                                
        var message = twitterContext.NewDirectMessage(auth.UserId, "Hi ucef, cool to discuss with you" + DateTime.Now);
        return View();
    }

但是因为auth.UserId为null,发生了异常,你知道吗?

1 个答案:

答案 0 :(得分:0)

这似乎与您之前的问题相同:

Send Private message with LinqToTwitter