/// <summary> /// 处理输出参数 /// </summary> /// <param name="resMsg"></param> /// <param name="method"></param> private void HandleEnd(ResponseMessage resMsg, System.Reflection.MethodInfo method) { if (resMsg.IsError) { return; } var invokeData = resMsg.Value as InvokeData; var pis = method.GetParameters().Where(p => p.ParameterType.IsByRef); if (pis.Count() > 0) { if (!string.IsNullOrEmpty(invokeData.OutParameters)) { var jobject = JObject.Parse(invokeData.OutParameters); if (jobject != null && jobject.Count > 0) { foreach (var p in pis) { var type = GetElementType(p.ParameterType); var jsonString = jobject[p.Name].ToString(Formatting.Indented); var obj = SerializationManager.DeserializeJson(type, jsonString); resMsg.Parameters[p.Name] = obj; } } } } //处理返回值 var returnType = GetElementType(method.ReturnType); resMsg.Value = SerializationManager.DeserializeJson(returnType, invokeData.Value); }
/// <summary> /// 读取服务 /// </summary> private IList <ServiceItem> ReaderService(out bool isError) { var serviceItems = new List <ServiceItem>(); try { //数据缓存1分钟 var url = string.Format(HTTP_PROXY_API, proxyServer, "api"); var jsonString = helper.Reader(url, 60); //将数据反系列化成对象 var items = SerializationManager.DeserializeJson <IList <ServiceItem> >(jsonString); serviceItems.AddRange(items); isError = false; } catch { isError = true; //TODO } return(serviceItems); }
private void HandleResponse(HTTPServerRequest request, HTTPServerResponse response) { //响应格式 response.ContentType = "application/json;charset=utf-8"; var pathAndQuery = request.URI.TrimStart('/'); var array = pathAndQuery.Split('?'); var methodName = array[0]; var paramString = array.Length > 1 ? array[1] : null; var callMethod = caller.GetCaller(methodName); if (callMethod == null) { response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_NOT_FOUND; var error = new HttpServiceResult { Message = string.Format("{0}【{1}】", response.Reason, methodName) }; SendResponse(response, error); return; } else if (callMethod.HttpMethod == HttpMethod.POST && request.Method.ToUpper() == "GET") { response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_METHOD_NOT_ALLOWED; var error = new HttpServiceResult { Message = response.Reason }; SendResponse(response, error); return; } try { //调用方法 NameValueCollection nvs = null; if (callMethod.HttpMethod == HttpMethod.GET) { nvs = HttpUtility.ParseQueryString(paramString ?? string.Empty, Encoding.UTF8); } else { //接收流内部数据 var stream = request.GetRequestStream(); //接收流内部数据 var sr = new StreamReader(stream, Encoding.UTF8); string streamValue = sr.ReadToEnd(); //转换成NameValueCollection nvs = ConvertCollection(streamValue); } if (callMethod.Authorized) { if (!request.Has("X-AuthParameter")) { throw new AuthorizeException("Request header did not exist [X-AuthParameter] info."); } else { //调用认证的信息 nvs[callMethod.AuthParameter] = request.Get("X-AuthParameter"); } } //转换成JsonString var parameters = ConvertJsonString(nvs); string jsonString = caller.CallMethod(methodName, parameters); if (callMethod.TypeString) { //如果返回是字符串类型,则设置为文本返回 response.ContentType = "text/plain;charset=utf-8"; //转换成string类型 jsonString = SerializationManager.DeserializeJson <string>(jsonString); } SendResponse(response, jsonString); } catch (HTTPMessageException ex) { response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_EXPECTATION_FAILED; var error = new HttpServiceResult { Message = string.Format("{0} - {1}", response.Reason, ex.Message) }; SendResponse(response, error); } catch (Exception ex) { response.StatusAndReason = HTTPServerResponse.HTTPStatus.HTTP_BAD_REQUEST; var e = ErrorHelper.GetInnerException(ex); var error = new HttpServiceResult { Message = string.Format("{0} - {1}", e.GetType().Name, e.Message) }; SendResponse(response, error); } }
/// <summary> /// 将字符串反系列化成对象 /// </summary> private object GetObject(Type type, string paramsKey) { string jsonString = WebHelper.GetRequestParam <string>(info.CurrentPage.Request, paramsKey, ""); return(SerializationManager.DeserializeJson(type, jsonString)); }
/// <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 }; } }