为了账号安全,请及时绑定邮箱和手机立即绑定

使用 LinqToTwitter 与 Twitter direct_messages/events

使用 LinqToTwitter 与 Twitter direct_messages/events

C#
慕盖茨4494581 2021-11-21 16:34:23
我真的被困在这好几天了。我在 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非常感谢!
查看完整描述

1 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

该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中的代码替换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()helper 方法,以便更轻松地了解何时必须对用户进行授权。


查看完整回答
反对 回复 2021-11-21
  • 1 回答
  • 0 关注
  • 166 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信