[WebInvoke(UriTemplate = "Qry?msg={xml}", Method = "POST")] public Stream SearchQry(string xml, Stream request) { WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; //将流转换为字符串 string requestData = new ParseUtil().StreamToString(request); //将字符串转换为流 return new ParseUtil().StringToStream(responseData); } /// <summary> /// 将流数据转换成字符串 /// </summary> /// <param name="stream"></param> /// <returns></returns> public string StreamToString(Stream stream) { string strData = string.Empty; try { byte[] bytes = streamToByteArray(stream); strData = Encoding.UTF8.GetString(bytes); //以字符串表示的流数据 } catch (Exception ex) { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(); System.Reflection.MethodBase methodBase = stackFrame.GetMethod(); LogUtil.LogException("方法:" + methodBase.ToString() + "\t异常信息:" + ex.Message + "\t【将流数据转换成字符串】方法发生错误"); } return strData; } /// <summary> /// 将流数据转换成字节数组 /// </summary> /// <param name="stream"></param> /// <returns></returns> private byte[] streamToByteArray(Stream stream) { byte[] buffer = new byte[32768]; byte[] bytesReturn = null; using (MemoryStream ms = new MemoryStream()) { while (true) { int read = stream.Read(buffer, 0, buffer.Length); if (read <= 0) //无数据时跳出循环 { break; } ms.Write(buffer, 0, read); } bytesReturn = ms.ToArray(); } stream.Close(); return bytesReturn; } /// <summary> /// 将字符串转换成流 /// </summary> /// <param name="stream"></param> /// <returns></returns> public Stream StringToStream(string xml) { try { xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + xml.Replace("\r\n", "").Replace(" ", ""); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(xml); Stream st = new MemoryStream(buffer); st.Flush(); st.Position = 0; return st; } catch (Exception ex) { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(); System.Reflection.MethodBase methodBase = stackFrame.GetMethod(); LogUtil.LogException("方法:" + methodBase.ToString() + "\t异常信息:" + ex.Message + "\t【将字符串转换成流】方法发生错误"); return null; } }