Пример #1
0
        /// <summary>
        /// 将服务解析成Http接口方法
        /// </summary>
        /// <param name="interfaceType"></param>
        /// <returns></returns>
        public virtual IList <HttpApiMethod> MethodResolver(Type interfaceType)
        {
            IList <HttpApiMethod> list = new List <HttpApiMethod>();
            var fileName = CoreHelper.GetFullPath("/config/httpapi.config");

            if (File.Exists(fileName))
            {
                try
                {
                    var xml = File.ReadAllText(fileName, Encoding.UTF8);
                    if (!string.IsNullOrEmpty(xml))
                    {
                        var config = SerializationManager.DeserializeXml <HttpApiConfig>(xml);
                        if (config != null && config.ApiServices != null)
                        {
                            var items = config.ApiServices.Where(p => !string.IsNullOrEmpty(p.FullName)).ToList();
                            var item  = items.FirstOrDefault(p => string.Compare(p.FullName, interfaceType.FullName, true) == 0);

                            //判断指定的服务是否在配置文件列表中
                            if (item != null && item.ApiItems != null)
                            {
                                list = ReadFromType(interfaceType, item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //写错误日志
                    SimpleLog.Instance.WriteLogForDir("httpapi", ex);
                }
            }

            return(list);
        }
Пример #2
0
        /// <summary>
        /// 获取相应
        /// </summary>
        /// <param name="returnType"></param>
        /// <returns></returns>
        public object GetResponse(Type returnType)
        {
            try
            {
                string         url     = GetRequestUrl();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.KeepAlive = false;
                if (timeout > 0)
                {
                    request.Timeout = timeout * 1000;
                }

                #region 处理Cookies

                //处理Cookies
                if (parameter.Cookies.Count > 0)
                {
                    CookieContainer container = new CookieContainer();
                    container.Add(request.RequestUri, parameter.Cookies);
                    request.CookieContainer = container;
                }

                #endregion

                //判断是否为POST方式
                if (parameter.DataObject != null && parameter.HttpMethod == HttpMethod.POST)
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Method      = parameter.HttpMethod.ToString();

                    var sb = new StringBuilder();
                    foreach (var kvp in parameter.DataObject)
                    {
                        var value = SerializationManager.SerializeJson(kvp.Value);
                        sb.AppendFormat("&{0}={1}", kvp.Key, HttpUtility.UrlEncode(value));
                    }

                    if (sb.Length > 0)
                    {
                        sb.Remove(0, 1);
                    }
                    var buffer = encoding.GetBytes(sb.ToString());

                    //设置流的长度
                    request.ContentLength = buffer.Length;

                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Flush();
                    }
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //读取响应流
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding))
                    {
                        string value = sr.ReadToEnd();
                        if (string.IsNullOrEmpty(value))
                        {
                            return(null);
                        }

                        var retType = returnType;

                        //如果是xml格式,则使用对象包装
                        if (parameter.DataFormat == DataFormat.XML)
                        {
                            if (returnType.IsValueType || returnType == typeof(string))
                            {
                                retType = typeof(RESTfulResponse);
                            }
                        }

                        object result = null;

                        //数据反序列化
                        if (parameter.DataFormat == DataFormat.JSON)
                        {
                            result = SerializationManager.DeserializeJson(retType, value);
                        }
                        else if (parameter.DataFormat == DataFormat.XML)
                        {
                            result = SerializationManager.DeserializeXml(retType, value);
                        }

                        if (retType == typeof(RESTfulResponse))
                        {
                            return(Convert.ChangeType((result as RESTfulResponse).Value, returnType));
                        }
                        else
                        {
                            return(result);
                        }
                    }
                }
                else
                {
                    throw new RESTfulException(response.StatusDescription)
                          {
                              Code = (int)response.StatusCode
                          };
                }
            }
            catch (WebException ex)
            {
                RESTfulResult result = null;
                try
                {
                    var stream = (ex.Response as HttpWebResponse).GetResponseStream();
                    using (var sr = new StreamReader(stream))
                    {
                        string content = sr.ReadToEnd();

                        if (parameter.DataFormat == DataFormat.JSON)
                        {
                            result = SerializationManager.DeserializeJson <RESTfulResult>(content);
                        }
                        else if (parameter.DataFormat == DataFormat.XML)
                        {
                            result = SerializationManager.DeserializeXml <RESTfulResult>(content);
                        }
                    }
                }
                catch { }

                if (result != null)
                {
                    throw new RESTfulException(result.Message)
                          {
                              Code = result.Code
                          };
                }
                else if (ex.Response != null)
                {
                    var res = ex.Response as HttpWebResponse;
                    throw new RESTfulException(res.StatusDescription)
                          {
                              Code = (int)res.StatusCode
                          };
                }
                else
                {
                    throw ex;
                }
            }
            catch (RESTfulException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new RESTfulException(ex.Message, ex)
                      {
                          Code = 404
                      };
            }
        }