Example #1
0
        public static ResponseInfo <TReturn> Delete <TReturn>(string url)
        {
            var items = UrlQueryParser.UrlToData(url).Item2;
            SortedList <string, object> list = new SortedList <string, object>();

            if (items != null)
            {
                foreach (var c in items)
                {
                    list.Add(c.Key, c.Value);
                }
            }

            var a = SignBuilder.BuildSignList(list, "", "");

            if (url.Contains('?'))
            {
                url += "&reqTime=" + a.ReqTime + "&sign=" + a.Sign;
            }
            else
            {
                url += "?reqTime=" + a.ReqTime + "&sign=" + a.Sign;
            }

            HttpClient httpClient = new HttpClient();
            Task <HttpResponseMessage> response = httpClient.DeleteAsync(url);
            var result = ConvertToResult <TReturn>(response);

            return(result);
        }
        /// <summary>
        /// Action执行前的过滤器
        /// </summary>
        /// <param name="actionContext">操作执行的上下文</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            //调试 记录
            ILog log = LogManager.GetLogger(this.GetType().Name);

            var method = actionContext.Request.Method;
            var client = GetClientIP(actionContext.Request);
            var reqUrl = client + "=>" + method.Method + "=>" + actionContext.Request.RequestUri.ToString();

            if (method.Method.ToUpper() == "GET" || method.Method.ToUpper() == "DELETE")
            {
                log.Debug(actionContext.Request.RequestUri);
                var    urlarguments = actionContext.Request.GetQueryNameValuePairs();
                string requestsign;
                string requesttime;

                if (!urlarguments.Any(o => o.Key.ToLower() == "reqtime"))
                {
                    throw new ArgumentException("URL不含请求参数reqTime!" + reqUrl);
                }
                requesttime = urlarguments.FirstOrDefault(o => o.Key.ToLower() == "reqtime").Value;
                actionContext.Request.Headers.Add("resTime", new string[1] {
                    requesttime
                });

                if (!urlarguments.Any(o => o.Key.ToLower() == "sign"))
                {
                    throw new ArgumentException("URL不含请求参数sign!" + reqUrl);
                }
                requestsign = urlarguments.FirstOrDefault(o => o.Key.ToLower() == "sign").Value;

                SortedList <string, object> slist = new SortedList <string, object>();

                foreach (var c in urlarguments)
                {
                    if (c.Key.ToLower() != "reqtime" && c.Key.ToLower() != "sign" && !string.IsNullOrWhiteSpace(c.Key))
                    {
                        slist.Add(c.Key, c.Value);
                    }
                }
                var sigh = SignBuilder.BuildSignList(slist, "", "", requesttime);
                if (requestsign != sigh.Sign)
                {
                    throw new ArgumentException("签名失败!" + reqUrl);
                }
                actionContext.ActionArguments.Remove(urlarguments.FirstOrDefault(o => o.Key.ToLower() == "reqtime").Key);
                actionContext.ActionArguments.Remove(urlarguments.FirstOrDefault(o => o.Key.ToLower() == "sign").Key);
                actionContext.Request.Headers.Add("resTime", new string[1] {
                    requesttime
                });
            }

            if (method.Method.ToUpper() == "POST" || method.Method.ToUpper() == "PUT")
            {
                var stream = actionContext.Request.Content.ReadAsStreamAsync();
                stream.Wait();
                Encoding encoding = Encoding.UTF8;
                stream.Result.Position = 0;
                string responseData = "";
                using (StreamReader reader = new StreamReader(stream.Result, encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }

                log.Debug(responseData);

                if (!string.IsNullOrWhiteSpace(responseData))
                {
                    var  urlarguments            = actionContext.Request.GetQueryNameValuePairs();
                    Type contenttype             = null;
                    var  httpParameterDescriptor = actionContext.ActionDescriptor.GetParameters().FirstOrDefault(o => urlarguments.All(m => o.ParameterName != m.Key));
                    if (httpParameterDescriptor != null)
                    {
                        contenttype = httpParameterDescriptor.ParameterType;
                    }

                    if (contenttype == null)
                    {
                        throw new Exception("无法识别参数!" + reqUrl);
                    }

                    Type   genericType     = typeof(RequestInfo <>);
                    Type[] templateTypeSet = new[] { contenttype };
                    Type   implementType   = genericType.MakeGenericType(templateTypeSet);
                    var    originpostdata  = Newtonsoft.Json.JsonConvert.DeserializeObject(responseData, implementType);

                    var datamap = implementType.GetProperty("dataMap").GetValue(originpostdata);
                    //if (datamap == null)
                    //{
                    //    throw new ArgumentException("content不含请求参数dataMap!");
                    //}

                    var odatetime = implementType.GetProperty("reqTime").GetValue(originpostdata);

                    if (odatetime == null)
                    {
                        throw new ArgumentException("content不含请求参数reqTime!" + reqUrl);
                    }
                    actionContext.Request.Headers.Add("resTime", new string[1] {
                        odatetime.ToString()
                    });
                    string datetime = implementType.GetProperty("reqTime").GetValue(originpostdata).ToString();

                    var oreqsign = implementType.GetProperty("sign").GetValue(originpostdata);

                    if (oreqsign == null)
                    {
                        throw new ArgumentException("content不含请求参数reqsign!" + reqUrl);
                    }

                    string reqsign = implementType.GetProperty("sign").GetValue(originpostdata).ToString();


                    var sigh = SignBuilder.BuildSign(datamap, "", "", datetime);
                    if (reqsign != sigh.Sign)
                    {
                        throw new ArgumentException("签名失败!" + reqUrl);
                    }
                    if (httpParameterDescriptor.ParameterName != null)
                    {
                        actionContext.ActionArguments.Remove(httpParameterDescriptor.ParameterName);
                        actionContext.ActionArguments.Add(httpParameterDescriptor.ParameterName, datamap);
                    }
                }
            }
            actionContext.Request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            base.OnActionExecuting(actionContext);
        }