Exemplo n.º 1
0
        public ApiResult Post(PostModel post)
        {
            if (!ModelState.IsValid)
            {
                var errorList = ModelState.Where(x => x.Value.Errors.Count > 0)
                                .ToDictionary(x => x.Key,
                                              x => x.Value.Errors.Select(e => e.ErrorMessage));
                return(apiResult(0, errorList));
            }

            try
            {
                var formData = JsonConvert.DeserializeObject <Dictionary <string, string> >(post.ApiRequest);

                // 需加入簽章
                if (post.IsNeedSignature)
                {
                    var tmp = formData.OrderBy(x => x.Key)
                              .Select(x => string.Format("{0}={1}", x.Key, x.Value));
                    string signature = CryptUtility.HMACSHA1(post.ApiKey, string.Join("&", tmp));
                    formData.Add("signature", signature);
                }

                // 財政部測試環境
                if (post.IsTestMode)
                {
                    post.ApiUrl = post.ApiUrl.Replace("//www.", "//wwwtest.")
                                  .Replace("//api.", "//wwwtest.");
                }

                var    query = formData.Select(x => string.Format("{0}={1}", x.Key, HttpUtility.UrlEncode(x.Value)));
                string url   = string.Format("{0}?{1}", post.ApiUrl.TrimEnd('?'), string.Join("&", query));

                if (post.IsClientMode)
                {
                    return(apiResult(100, url));
                }
                else
                {
                    string result = null;
                    using (HttpClient hc = new HttpClient())
                    {
                        // 30 秒 Time Out
                        hc.Timeout = TimeSpan.FromSeconds(30);
                        result     = hc.GetStringAsync(url).Result;
                    }
                    return(apiResult(1, new
                    {
                        url,
                        result
                    }));
                }
            }
            catch (Exception ex)
            {
                return(apiResult(-1, ex.Message));
            }
        }