oauth / token返回空体

时间:2012-11-15 20:44:27

标签: c# oauth dotnetopenauth access-token

我在使用oauth在客户端应用程序中获取access_token时遇到问题。 返回的响应具有空体,但在API中我可以看到响应不为空。

tokenresponse = { 
   "access_token":"[ACCESSTOKENVALUE]",
   "token_type":"bearer",
   "expires_in":"1200",
   "refresh_token":"[REFRESHTOKENVALUE]",
   "scope":"[SCOPEVALUE]"
} 

API中返回令牌http://api.sample.com/OAuth/Token的方法:

public ActionResult Token()
{
     OutgoingWebResponse response =
     this.AuthorizationServer.HandleTokenRequest(this.Request);
     string tokenresponse = string.Format("Token({0})", response!=null?response.Body:"")); 
     return response.AsActionResult();
} 

请求令牌的客户端方法是:

        public string GetAuthorizationToken(string code)
        { 
            string Url = ServerPath + "OAuth/Token"; 
            string redirect_uri_encode = UrlEncode(ClientPath);
            string param =  string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);

            HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
            string result = null;
            request.Method = "POST";
            request.KeepAlive = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 10000;
            request.Headers.Remove(HttpRequestHeader.Cookie);
            var bs = Encoding.UTF8.GetBytes(param);
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            using (WebResponse response = request.GetResponse())
            {  
                var sr = new StreamReader(response.GetResponseStream());
                result = sr.ReadToEnd();
                sr.Close();
            } 
            if (!string.IsNullOrEmpty(result))
            {
                TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
                return UpdateAuthorizotionFromToken(tokendata);
            } 
            return null;
        } 

结果变量为空。 如果您知道可能导致这种情况的原因,请告诉我。最初我假设是因为cookie,所以我试图将它们从请求中删除。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

亲爱的,只需使用以下代码创建webclient即可获得令牌信息中的json信息。我使用它并简单地使用它。

        WebClient client = new WebClient();
        string postData = "client_id=" + ""
                        + "&client_secret=" + ""
                        + "&grant_type=password&username=" + "" //your username
                        + "&password=" + "";//your password :)
        string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
        string tokenInfo = client.UploadString(soundCloudTokenRes, postData);

然后,您可以使用仅包含来自tokeninfo的令牌的子字符串。 在声音云上上传曲目。

private void TestSoundCloudupload()         {

        System.Net.ServicePointManager.Expect100Continue = false;
        var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
        //some default headers
        request.Accept = "*/*";
        request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
        request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
        request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");

        //file array
        var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
        //other form data
        var form = new NameValueCollection();
        form.Add("track[title]", "Some title");
        form.Add("track[sharing]", "public");
        form.Add("oauth_token", "");
        form.Add("format", "json");

        form.Add("Filename", "0.mp3");
        form.Add("Upload", "Submit Query");
        try
        {
            using (var response = HttpUploadHelper.Upload(request, files, form))
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    Response.Write(reader.ReadToEnd());
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }