在MVC中获取推文

时间:2016-04-08 17:55:45

标签: c# asp.net-mvc twitter

我正在尝试加载推文但我的代码在使用我的MVC应用时无效。但是,使用控制台时,确切的代码可以正常工作。

我认为它与“异步”有关,我之前没有使用过这方面的经验,我无法找到解决方案。 “GetAccessToken()”未命中后的断点

在我的控制器中:

    public ActionResult Tweets(int tweets, string username)
    {
        var twitter = new Twitter();

        var userTweets = twitter.GetTweets("chrishall9521", 10).Result.ToList();

        this.ViewBag.Tweets = userTweets;

        return View();
    }

在我的“Twitter”课程中:

    public async Task<IEnumerable<string>> GetTweets(string userName, int count)
    {
        var accessToken = await GetAccessToken();
        var requestUserTimeline = new HttpRequestMessage(HttpMethod.Get, string.Format("https://api.twitter.com/1.1/statuses/user_timeline.json?count={0}&screen_name={1}&trim_user=1&exclude_replies=1", count, userName));
        requestUserTimeline.Headers.Add("Authorization", "Bearer " + accessToken);
        var httpClient = new HttpClient();
        HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);
        var serializer = new JavaScriptSerializer();
        dynamic json = serializer.Deserialize<object>(await responseUserTimeLine.Content.ReadAsStringAsync());
        var enumerableTwitts = (json as IEnumerable<dynamic>);

        if (enumerableTwitts == null)
        {
            return null;
        }

        return enumerableTwitts.Select(t => (string)(t["text"].ToString()));
    }

    public async Task<string> GetAccessToken()
    {
        var httpClient = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
        var customerInfo = Convert.ToBase64String(new UTF8Encoding().GetBytes(OAuthConsumerKey + ":" + OAuthConsumerSecret));
        request.Headers.Add("Authorization", "Basic " + customerInfo);
        request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");

        var response = await httpClient.SendAsync(request).ConfigureAwait(false);

        string json = await response.Content.ReadAsStringAsync();
        var serializer = new JavaScriptSerializer();
        dynamic item = serializer.Deserialize<object>(json);
        return item["access_token"];
    }

1 个答案:

答案 0 :(得分:2)

不要那样使用.Result - 你就是死锁。请改用await方法中的Tweets,然后将其设为async。使用async的基本“黄金法则”是,当您使用它时,您将一直使用它。

这是一个blog post,其中有类似的例子供进一步阅读。