使用LinqToTwitter异步并等待Twitter direct_messages / events

时间:2018-08-09 13:22:25

标签: c# asp.net twitter async-await linq-to-twitter

我真的被这几天困扰了。我正在使用LinqToTwitter和ASP.Net C#

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

我希望该功能在单击按钮时起作用,所以我尝试的是:

  1. BtnClick:

`

protected void Btn1_Click(object sender, EventArgs e)
        {
            string x = MyTest().Result;
        }

`

  1. MyTest:

`

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;
}

`

  1. DoAuthorization:

`

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;
    }`

任何帮助将非常感激!

1 个答案:

答案 0 :(得分:1)

代码中的DoAuthorization()看起来像来自控制台示例,并且不适用于ASP.NET。原因是ASP.NET是无状态的,并且OAuth流程将您带到Twitter站点并返回。因此,您必须将授权分为两部分:开始和完成。

我猜您正在使用ASP.NET MVC,但是如果您使用的是WebForms,则概念相似(但不同)。这是开始部分:

public class OAuthController : AsyncController
{
    public ActionResult Index()
    {
        return View();
    }

    public async Task<ActionResult> BeginAsync()
    {
        var auth = new MvcAuthorizer
        {
            CredentialStore = new SessionStateCredentialStore
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
            }
        };

请注意,它使用MvcAuthorizer填充凭据。拥有MvcAuthorizer实例后,将用户重定向到Twitter进行授权,如下所示:

        string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
        return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
    }

这会将用户发送到Twitter授权页面,在该页面上,他们授予您的应用程序代表其操作的权限。 Twitter将用户重定向回twitterCallback,这就是为什么上面的代码修改了URL并将URL中的Begin替换为Complete的原因。因此,Twitter将用户重定向回您的应用,该应用将调用以下CompleteAsync()操作:

    public async Task<ActionResult> CompleteAsync()
    {
        var auth = new MvcAuthorizer
        {
            CredentialStore = new SessionStateCredentialStore()
        };

        await auth.CompleteAuthorizeAsync(Request.Url);

        // This is how you access credentials after authorization.
        // The oauthToken and oauthTokenSecret do not expire.
        // You can use the userID to associate the credentials with the user.
        // You can save credentials any way you want - database, 
        //   isolated storage, etc. - it's up to you.
        // You can retrieve and load all 4 credentials on subsequent 
        //   queries to avoid the need to re-authorize.
        // When you've loaded all 4 credentials, LINQ to Twitter will let 
        //   you make queries without re-authorizing.
        //
        //var credentials = auth.CredentialStore;
        //string oauthToken = credentials.OAuthToken;
        //string oauthTokenSecret = credentials.OAuthTokenSecret;
        //string screenName = credentials.ScreenName;
        //ulong userID = credentials.UserID;
        //

        return RedirectToAction("Index", "Home");
    }

现在,您的应用拥有用户的权限,可以抓住他们的令牌并保留它们以进行后续查询,这样您就不必在每次用户想要使用您的应用时都继续执行OAuth流程。请参阅代码中有关如何获取这些凭据的注释。

现在,当您要执行查询时,像这样实例化一个MvcAuthorizer

static async Task<string> mytest()
{
    var auth = new MvcAuthorizer
    {
        CredentialStore = new SessionStateCredentialStore()
    };

    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;

}

您可以看到修改后的myTest()方法的第一条语句如何用MvcAuthorizer实例化SessionStateCredentialStore并保持凭据。

最后,在您希望用户使用Twitter授权应用程序的时间点(登录,第一次查询或您选择的其他任何时间),检查它们是否已被授权,然后重新如果不是,则直接输入,例如:

    public ActionResult Index()
    {
        if (!new SessionStateCredentialStore().HasAllCredentials())
            return RedirectToAction("Index", "OAuth");

        return View();
    }

注意上面的代码如何在HasAllCredentials()实例上调用SessionStateCredentialStore。我假设您将添加自己的逻辑来确定何时加载用户的凭据,但是希望您了解HasAllCredentials()帮助方法,以便更轻松地知道何时必须授权用户。

有关更多信息,请访问LINQ to Twitter OAuth docs。 LINQ to Twitter源代码也有Samples on how to use OAuth