private AlibabaException GetAlibabaException(WebException webException)
        {
            AlibabaException alibabaException = null;

            byte[] buffer = this.m_bufferManager.TakeBuffer(BUFFER_POOL_ITEM_SIZE);

            try {
                using (HttpWebResponse response = (HttpWebResponse)webException.Response) {
                    if (response != null)
                    {
                        string content = response.GetResponseString(buffer);

                        ChinaAlibabaErrorInfo info = this.m_jsonSerializer.Deserialize <ChinaAlibabaErrorInfo>(content);
                        alibabaException = new AlibabaException(info.error_description ?? info.error_message, (int)response.StatusCode, webException);
                    }
                    else
                    {
                        alibabaException = new AlibabaException(webException.Message, 500, webException);
                    }
                }
            } catch (Exception ex) {
                alibabaException = new AlibabaException(string.Format("Error occurred when parse error response: {0}", ex.Message), 500, ex);
            } finally {
                this.m_bufferManager.ReturnBuffer(buffer);
            }

            return(alibabaException);
        }
        private void ProcessReturnValue <TReturn>(Exception error, string content, Action <Exception, TReturn> callback)
        {
            TReturn value = default(TReturn);

            if (error == null && content != null)
            {
                try {
                    value = this.m_jsonSerializer.Deserialize <TReturn>(content);
                } catch (Exception ex) {
                    error = new AlibabaException(string.Format("Error occurred when parse response content: {0}", ex.Message), 500, ex);
                }
            }
            callback(error, value);
        }
        private void SendHttpRequest(HttpWebRequest request, Action <Exception, string> callback)
        {
            NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetResponse((ar) => {
                string content  = null;
                Exception error = null;
                byte[] buffer   = this.m_bufferManager.TakeBuffer(BUFFER_POOL_ITEM_SIZE);

                try {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar)) {
                        content = response.GetResponseString(buffer);
                    }
                } catch (WebException ex) {
                    error = this.GetAlibabaException(ex);
                } catch (Exception ex) {
                    error = new AlibabaException(string.Format("Error occurred when send HTTP request: {0}", ex.Message), 500, ex);
                } finally {
                    this.m_bufferManager.ReturnBuffer(buffer);
                }

                callback(error, content);
            }, null), request, this.m_timeout);
        }
        private void SendPostRequest(string url, IDictionary <string, string> args, Encoding encoding, Action <Exception, string> callback)
        {
            HttpWebRequest request     = this.CreateRequest(url, WebRequestMethods.Http.Post, encoding);
            string         queryString = AlibabaHelper.GetQueryString(args, encoding ?? this.m_defaultEncoding);

            byte[] data = queryString.Length > 0 ? (encoding ?? this.m_defaultEncoding).GetBytes(queryString) : null;

            if (data != null)
            {
                request.ContentLength = data.Length;
                NetworkRequestAsyncTimeout.RegisterRequest(request.BeginGetRequestStream((ar) => {
                    Exception error = null;

                    try {
                        using (Stream writer = request.EndGetRequestStream(ar)) {
                            writer.Write(data, 0, data.Length);
                        }
                    } catch (WebException ex) {
                        error = this.GetAlibabaException(ex);
                    } catch (Exception ex) {
                        error = new AlibabaException(string.Format("Error occurred when send POST data: {0}", ex.Message), 500, ex);
                    }

                    if (error != null)
                    {
                        callback(error, null);
                    }
                    else
                    {
                        this.SendHttpRequest(request, callback);
                    }
                }, null), request, this.m_timeout);
            }
            else
            {
                this.SendHttpRequest(request, callback);
            }
        }
Example #5
0
        /// <summary>
        /// 接受回调请求后向平台换取Token。
        /// </summary>
        /// <param name="application">应用信息。</param>
        /// <param name="callbackRequest">回调请求。</param>
        public override async Task<AuthorizationResult> GetTokenAsync(Application application, HttpRequest callbackRequest)
        {

            #region 获取Token请求参数

            //从请求报文中获取签名
            string code = callbackRequest.Params["Code"];
            //授权类型,使用authorization_code即可
            string grant_type = "authorization_code";
            //是否需要返回refresh_token,如果返回了refresh_token,原来获取的refresh_token也不会失效,除非超过半年有效期
            string need_refresh_token = "true";
            //app唯一标识,即appKey
            string client_id = application.AppKey;
            //app密钥
            string client_secret = application.Secret;
            //app入口地址
            string redirect_uri = application.RedirectUrl;

            #endregion

            #region 生成请求URL
            string url = application.Platform.TokenUrl.Replace("YOUR_APPKEY", application.AppKey);
            string para = string.Format("grant_type={0}&need_refresh_token={1}&client_id= {2}&client_secret= {3}&redirect_uri={4}&code={5}",
                grant_type, need_refresh_token, client_id, client_secret, redirect_uri, code);

            #endregion

            #region 发送请求及返回结果

            try
            {
                //发送请求报文
                string json = await HttpHelp.GetStrAsync(url + "?" + para);
                //判断是否返回异常
                if (json.Contains("error"))
                {
                    AlibabaException alibabaException = await Task.Factory.StartNew(() => { return JsonConvert.DeserializeObject<AlibabaException>(json); });
                    //抛出异常
                    if (string.IsNullOrWhiteSpace(alibabaException.Error))
                    {
                        throw EtpException.Create(application.Platform.Name, alibabaException.Error_code.ToString(), alibabaException.Error_message, "", "");
                    }
                    else
                    {
                        throw EtpException.Create(application.Platform.Name, alibabaException.Error, alibabaException.Error_description, "", "");
                    }
                }
                else
                {
                    //把返回的json字符串反序列化
                    AlibabaJson alibabaJson = await Task.Factory.StartNew(() => { return JsonConvert.DeserializeObject<AlibabaJson>(json); });
                    //填充AuthorizationResult数据
                    return new AuthorizationResult()
                    {
                        Token = alibabaJson.Access_token,
                        OpenId =alibabaJson.AliId,
                        RefreshToken = alibabaJson.Refresh_token,
                        UserName = alibabaJson.MemberId,
                        ExpireAt = DateTime.Now.AddMinutes(-1).AddSeconds(alibabaJson.Expires_in),
                        RefreshExpireAt = DateTime.Parse(alibabaJson.Refresh_token_timeout.Substring(0, 4) + "-" +
                        alibabaJson.Refresh_token_timeout.Substring(4, 2) + "-" +
                        alibabaJson.Refresh_token_timeout.Substring(6, 2) + " " +
                        alibabaJson.Refresh_token_timeout.Substring(8, 2) + ":" +
                        alibabaJson.Refresh_token_timeout.Substring(10, 2) + ":" +
                        alibabaJson.Refresh_token_timeout.Substring(12, 2))
                    };
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            #endregion
        }