使用 LinqToTwitter 与 Twitter direct_messages/events

我真的被困在这好几天了。我在 ASP.Net C# 中使用 LinqToTwitter


我正在尝试让新的 DirectMessages 工作,我遵循了示例但没有运气。


我希望该功能适用于按钮单击,所以我尝试的是:


Btn点击:

`


protected void Btn1_Click(object sender, EventArgs e)

        {

            string x = MyTest().Result;

        }

`


我的测试:

`


static async Task<string> mytest()

{

        AspNetAuthorizer auth = DoAuthorization();

        var twitterCtx = new TwitterContext(auth);

        List<DMEvent> AllDmEvents = new List<DMEvent>();

        string Cursor;

        DirectMessageEvents dmResponse =

            await

                (from dm in twitterCtx.DirectMessageEvents

                 where dm.Type == DirectMessageEventsType.List &&

                 dm.Count == 10

                 select dm)

                .SingleOrDefaultAsync(); //In debugging mode, after this line is executed, it will go away and keep loading forever and never come back

        AllDmEvents.AddRange(dmResponse.Value.DMEvents);

        Cursor = dmResponse.Value.NextCursor;

        string xxx = (JsonConvert.SerializeObject(AllDmEvents, Formatting.None));

        return xxx;

}

`


做授权:

`


static AspNetAuthorizer DoAuthorization()

    {

        AspNetAuthorizer auth = new AspNetAuthorizer();

        auth = new AspNetAuthorizer

        {

            CredentialStore = new SessionStateCredentialStore

            {

                ConsumerKey = "MyConsumerKey",

                ConsumerSecret = "MyConsumerSecret ",

                OAuthToken = "MyOAuthToken ",

                OAuthTokenSecret = "MyOAuthTokenSecret ",

                ScreenName = "MyUserName",

                UserID = 12345678

            }

        };

        return auth;

    }`

任何帮助将SO非常感谢!


慕盖茨4494581
浏览 167回答 1
1回答

手掌心

该DoAuthorization()在你的代码看起来它从控制台样本来了,不会与ASP.NET工作。原因是 ASP.NET 是无状态的,并且 OAuth 过程将您带到 Twitter 站点并返回。因此,您必须将授权分成两部分:开始和完成。我猜您使用的是 ASP.NET MVC,但如果您使用的是 WebForms,则概念相似(但不同)。这是开始部分:public class OAuthController : AsyncController{&nbsp; &nbsp; public ActionResult Index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }&nbsp; &nbsp; public async Task<ActionResult> BeginAsync()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var auth = new MvcAuthorizer&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CredentialStore = new SessionStateCredentialStore&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };请注意,它使用一个MvcAuthorizer,填充凭据。获得MvcAuthorizer实例后,将用户重定向到 Twitter 进行授权,如下所示:&nbsp; &nbsp; &nbsp; &nbsp; string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");&nbsp; &nbsp; &nbsp; &nbsp; return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));&nbsp; &nbsp; }将用户发送到 Twitter 授权页面,在那里他们授予您的应用程序代表他们操作的权限。Twitter将用户重定向回twitterCallback,这也是为什么上述修改URL中的代码替换Begin与Complete您的网址。因此,Twitter 将用户重定向回您的应用程序,该应用程序调用以下CompleteAsync()操作:&nbsp; &nbsp; public async Task<ActionResult> CompleteAsync()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var auth = new MvcAuthorizer&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CredentialStore = new SessionStateCredentialStore()&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; await auth.CompleteAuthorizeAsync(Request.Url);&nbsp; &nbsp; &nbsp; &nbsp; // This is how you access credentials after authorization.&nbsp; &nbsp; &nbsp; &nbsp; // The oauthToken and oauthTokenSecret do not expire.&nbsp; &nbsp; &nbsp; &nbsp; // You can use the userID to associate the credentials with the user.&nbsp; &nbsp; &nbsp; &nbsp; // You can save credentials any way you want - database,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;isolated storage, etc. - it's up to you.&nbsp; &nbsp; &nbsp; &nbsp; // You can retrieve and load all 4 credentials on subsequent&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;queries to avoid the need to re-authorize.&nbsp; &nbsp; &nbsp; &nbsp; // When you've loaded all 4 credentials, LINQ to Twitter will let&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp;you make queries without re-authorizing.&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; //var credentials = auth.CredentialStore;&nbsp; &nbsp; &nbsp; &nbsp; //string oauthToken = credentials.OAuthToken;&nbsp; &nbsp; &nbsp; &nbsp; //string oauthTokenSecret = credentials.OAuthTokenSecret;&nbsp; &nbsp; &nbsp; &nbsp; //string screenName = credentials.ScreenName;&nbsp; &nbsp; &nbsp; &nbsp; //ulong userID = credentials.UserID;&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; return RedirectToAction("Index", "Home");&nbsp; &nbsp; }既然您的应用程序拥有用户的权限,请获取他们的令牌并保留它们以供后续查询使用,这样您就不必每次用户想要使用您的应用程序时都继续 OAuth 过程。请参阅代码中有关如何获取这些凭据的说明。现在,当您要执行查询时,实例化一个MvcAuthorizer,如下所示:static async Task<string> mytest(){&nbsp; &nbsp; var auth = new MvcAuthorizer&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; CredentialStore = new SessionStateCredentialStore()&nbsp; &nbsp; };&nbsp; &nbsp; var twitterCtx = new TwitterContext(auth);&nbsp; &nbsp; List<DMEvent> AllDmEvents = new List<DMEvent>();&nbsp; &nbsp; string Cursor;&nbsp; &nbsp; DirectMessageEvents dmResponse =&nbsp; &nbsp; &nbsp; &nbsp; await&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (from dm in twitterCtx.DirectMessageEvents&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;where dm.Type == DirectMessageEventsType.List &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dm.Count == 10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select dm)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .SingleOrDefaultAsync(); //In debugging mode, after this line is executed, it will go away and keep loading forever and never come back&nbsp; &nbsp; AllDmEvents.AddRange(dmResponse.Value.DMEvents);&nbsp; &nbsp; Cursor = dmResponse.Value.NextCursor;&nbsp; &nbsp; string xxx = (JsonConvert.SerializeObject(AllDmEvents, Formatting.None));&nbsp; &nbsp; return xxx;}你可以看到你修改的第一个语句如何myTest()方法实例MvcAuthorizer有SessionStateCredentialStore,牵着你的凭据。最后,在您希望用户使用 Twitter 授权您的应用程序的时间点(登录、第一次查询或您选择的任何其他时间),检查他们是否已经获得授权,如果没有,请重新定向, 像这样:&nbsp; &nbsp; public ActionResult Index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!new SessionStateCredentialStore().HasAllCredentials())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return RedirectToAction("Index", "OAuth");&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }注意上面的代码如何调用HasAllCredentials()一个SessionStateCredentialStore实例。我假设您将添加自己的逻辑来确定何时加载用户的凭据,但希望您了解HasAllCredentials()helper 方法,以便更轻松地了解何时必须对用户进行授权。
打开App,查看更多内容
随时随地看视频慕课网APP