亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 184 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號