如何从控制器中使用第三方Web服务?

时间:2014-01-14 19:40:47

标签: asp.net-mvc web-services

我想从控制器中消耗部分Twitter API,这样我就可以在没有用户启用javascript的情况下提供内容。

我打算创建一个代理控制器来管理API uri和身份验证令牌,但我不确定如何从后端进行实际的服务调用。我更愿意将返回的数据复制到实体对象中,以便我可以在视图中轻松地对它们进行格式化。

是否有关于我需要使用的类集的这些或文档的示例?

2 个答案:

答案 0 :(得分:4)

如果您想创建一个Web请求,这是一个示例:

(pData可以是web api的参数)

    private string _callWebService(string pUrl, string pData)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pUrl);
            request.Method = "POST";
            request.ContentType = "...";
            byte[] bytes = Encoding.UTF8.GetBytes(pData);
            request.ContentLength = bytes.Length;

            using (var writer = request.GetRequestStream())
            {
                writer.Write(bytes, 0, bytes.Length);
            }

            using(var response = (HttpWebResponse)request.GetResponse())
            {
                 if (response.StatusCode.ToString().ToLower() == "ok")
                 {
                    using(var contentReader = new StreamReader(response.GetResponseStream()))
                    {
                        return contentReader.ReadToEnd();
                    }
                 }
             }
        }
        catch (Exception)
        {
            return string.Empty;
        }
        return string.Empty;
    }

答案 1 :(得分:0)

您需要使用的实际代码如下,这将验证并检索用户的时间轴。

这是我去年的问题,我在问题中提到的Github项目和nuget安装中有一个MVC项目的例子。您可以使用nuget包或只是从Github复制代码。

Authenticate and request a user's timeline with Twitter API 1.1 oAuth

// You need to set your own keys and screen name
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "aScreenName";

// Do the Authenticate
var authHeaderFormat = "Basic {0}";

var authHeader = string.Format(authHeaderFormat,
    Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
    Uri.EscapeDataString((oAuthConsumerSecret)))
));

var postBody = "grant_type=client_credentials";

HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using (Stream stream = authRequest.GetRequestStream())
{
    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
    stream.Write(content, 0, content.Length);
}

authRequest.Headers.Add("Accept-Encoding", "gzip");

WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
    using (var reader = new StreamReader(authResponse.GetResponseStream())) {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objectText = reader.ReadToEnd();
        twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
    }
}

// Do the timeline
var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
var timelineUrl = string.Format(timelineFormat, screenname);
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
timeLineRequest.Method = "Get";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
    using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
    {
         timeLineJson = reader.ReadToEnd();
    }
}


public class TwitAuthenticateResponse {
    public string token_type { get; set; }
    public string access_token { get; set; }
}