void ValidateMessageBody(ref System.ServiceModel.Channels.Message message, bool isRequest) { if (!message.IsFault) { XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas(); XmlReader bodyReader = message.GetReaderAtBodyContents().ReadSubtree(); XmlReaderSettings wrapperSettings = new XmlReaderSettings(); wrapperSettings.CloseInput = true; wrapperSettings.Schemas = schemaSet; wrapperSettings.ValidationFlags = XmlSchemaValidationFlags.None; wrapperSettings.ValidationType = ValidationType.Schema; wrapperSettings.ValidationEventHandler += new ValidationEventHandler(InspectionValidationHandler); XmlReader wrappedReader = XmlReader.Create(bodyReader, wrapperSettings); // pull body into a memory backed writer to validate this.isRequest = isRequest; MemoryStream memStream = new MemoryStream(); XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateBinaryWriter(memStream); xdw.WriteNode(wrappedReader, false); xdw.Flush(); memStream.Position = 0; XmlDictionaryReader xdr = XmlDictionaryReader.CreateBinaryReader(memStream, quotas); // reconstruct the message with the validated body Message replacedMessage = Message.CreateMessage(message.Version, null, xdr); replacedMessage.Headers.CopyHeadersFrom(message.Headers); replacedMessage.Properties.CopyProperties(message.Properties); message = replacedMessage; } }
object IClientMessageFormatter.DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters) { object returnValue = null; XmlDictionaryReader bodyContentReader = message.GetReaderAtBodyContents(); bodyContentReader.ReadStartElement(XmlRpcProtocol.MethodResponse); bodyContentReader.ReadStartElement(XmlRpcProtocol.Params); if (bodyContentReader.IsStartElement(XmlRpcProtocol.Param)) { bodyContentReader.ReadStartElement(); if (bodyContentReader.IsStartElement(XmlRpcProtocol.Value)) { bodyContentReader.ReadStartElement(); if (bodyContentReader.NodeType == XmlNodeType.Text) { returnValue = bodyContentReader.ReadContentAs(_returnParameter.ParameterType, null); } else { returnValue = XmlRpcDataContractSerializationHelper.Deserialize(bodyContentReader, _returnParameter.ParameterType); } bodyContentReader.ReadEndElement(); } bodyContentReader.ReadEndElement(); bodyContentReader.ReadEndElement(); } bodyContentReader.Close(); return returnValue; }
public string SelectOperation(ref System.ServiceModel.Channels.Message message) { XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); message = CreateMessageCopy(message, bodyReader); message.Headers.Action = bodyReader.NamespaceURI + @"/" + bodyReader.LocalName; return bodyReader.LocalName; }
private static XmlRpcMessage CreateXmlRpcMessage(System.ServiceModel.Channels.Message message) { XmlDictionaryReader messageReader = message.GetReaderAtBodyContents(); string methodName; do { if (messageReader.IsStartElement(XmlRpcProtocol.MethodCall)) { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (!messageReader.IsStartElement(XmlRpcProtocol.MethodName)) { throw new XmlRpcFormatException(Properties.Resources.EXCEPTION_MISSING_METHODNAME); } else { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (messageReader.NodeType == XmlNodeType.Text) { methodName = messageReader.ReadString(); messageReader.ReadEndElement(); } else { throw new XmlRpcFormatException(Properties.Resources.EXCEPTION_MISSING_METHODNAME); } if (messageReader.IsStartElement(XmlRpcProtocol.Params)) { return new XmlRpcMessage(methodName, messageReader, true); } else { messageReader.Close(); return new XmlRpcMessage(methodName); } } } else if (messageReader.IsStartElement(XmlRpcProtocol.MethodResponse)) { messageReader.ReadStartElement(); messageReader.MoveToContent(); if (messageReader.IsStartElement(XmlRpcProtocol.Params)) { return new XmlRpcMessage(messageReader); } else { messageReader.Close(); return new XmlRpcMessage(); } } } while (messageReader.Read()); throw new XmlRpcFormatException(Properties.Resources.EXCEPTION_INVALID_MESSAGE); }
public string SelectOperation(ref System.ServiceModel.Channels.Message message) { // When WCF throw "This message cannot support the operation because it has been read" exception, see the following link to fix. //http://stackoverflow.com/a/11170390/2814166 XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); //XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI); message = CreateMessageCopy(message, bodyReader); return bodyReader.LocalName; }
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { if (reply != null && reply.Version == MessageVersion.Soap11) { if (reply.IsFault) { throw new RawFaultException(reply.GetReaderAtBodyContents()); } } }
public string SelectOperation(ref System.ServiceModel.Channels.Message message) { XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI); message = CreateMessageCopy(message,bodyReader); if (dispatchDictionary.ContainsKey(lookupQName)) { return dispatchDictionary[lookupQName]; } else { return defaultOperationName; } }
/// <summary> /// Request IMessageInspector implementation, decodes message raw data as URL-encoded, passes decoded data to FormData message property /// </summary> /// <param name="request"></param> /// <param name="channel"></param> /// <param name="instanceContext"></param> /// <returns></returns> public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext) { if (request.IsEmpty || request.Properties[HttpOperationName].ToString() != Operation.Name) return null; var contentType = ((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers[ContentTypeHeader]; if (contentType == null) throw new WebFaultException(System.Net.HttpStatusCode.NotAcceptable); if (contentType != null && contentType.StartsWith(MessageContentTypes.Form)) { byte[] rawContent = null; using (var contentStream = request.GetReaderAtBodyContents()) rawContent = contentStream.ReadContentAsBase64(); string rawTextContent = rawContent != null ? Encoding.UTF8.GetString(rawContent) : null; if (SeemsUrlEncoded(rawTextContent)) { var formData = HttpUtility.ParseQueryString(rawTextContent); request.Properties.Add(HtmlFormDataPropertyKey, formData); return formData; } } return null; }
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { if (correlationState != null && correlationState is string) { // if we have a JSONP callback then buffer the response, wrap it with the // callback call and then re-create the response message string callback = (string)correlationState; bool bodyIsText = false; HttpResponseMessageProperty response = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (response != null) { string contentType = response.Headers["Content-Type"]; if (contentType != null) { // Check the response type and change it to text/javascript if we know how. if (contentType.StartsWith("text/plain", StringComparison.InvariantCultureIgnoreCase)) { bodyIsText = true; response.Headers["Content-Type"] = "text/javascript;charset=utf-8"; } else if (contentType.StartsWith("application/json", StringComparison.InvariantCultureIgnoreCase)) { response.Headers["Content-Type"] = contentType.Replace("application/json", "text/javascript"); } } } XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.ReadStartElement(); string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64()); if (bodyIsText) { // Escape the body as a string literal. content = "\"" + QuoteJScriptString(content) + "\""; } content = callback + "(" + content + ")"; System.ServiceModel.Channels.Message newreply = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.None, "", new Writer(content)); newreply.Properties.CopyProperties(reply.Properties); reply = newreply; } }
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { if (correlationState != null && correlationState is string) { // if we have a JSONP callback then buffer the response, wrap it with the // callback call and then re-create the response message string callback = (string)correlationState; XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.ReadStartElement(); string content = JSONPSupportInspector.encoding.GetString(Convert.FromBase64String(reader.Value)); content = callback + "(" + content + ")"; Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(content)); newreply.Properties.CopyProperties(reply.Properties); reply = newreply; } }
public object DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters) { MessageDescription incomingMessage = this.operationDescription.Messages[1]; MessagePartDescription returnPart = incomingMessage.Body.ReturnValue; XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); if (incomingMessage.Body.WrapperName != null) { bool isEmptyElement = bodyReader.IsEmptyElement; bodyReader.ReadStartElement(incomingMessage.Body.WrapperName, incomingMessage.Body.WrapperNamespace); if (isEmptyElement) return null; } XmlObjectSerializer returnValueSerializer = this.serializerOperationBehavior.CreateSerializer( returnPart.Type, returnPart.Name, returnPart.Namespace, this.knownTypes); object result = returnValueSerializer.ReadObject(bodyReader, false); if (incomingMessage.Body.WrapperName != null) { bodyReader.ReadEndElement(); } return result; }
/// <summary> /// Gets the method message. /// </summary> /// <param name="message">The message.</param> /// <returns>WCF Method Message</returns> public WCFMethodMessage GetMethodMessage(ref System.ServiceModel.Channels.Message message) { string action = message.Headers.Action; WCFMethodMessage methodMessage = null; if (!string.IsNullOrEmpty(action)) { if (this.Methods.ContainsKey(action)) { methodMessage = this.Methods[action]; } } if (methodMessage == null) { try { XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); string root = bodyReader.LocalName; WCFMethodMessage methodMessage2 = this.Methods.Values.FirstOrDefault(s => string.Compare(s.Input, root, true) == 0); if (methodMessage2 != null) { methodMessage = methodMessage2; Message message2 = Message.CreateMessage(message.Version, methodMessage2.Action, bodyReader); message = message2; } } finally { } } return methodMessage; }
void IDispatchMessageFormatter.DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters) { int paramCounter = 0; XmlDictionaryReader bodyContentReader = message.GetReaderAtBodyContents(); bodyContentReader.ReadStartElement(XmlRpcProtocol.Params); if (parameters.Length > 0) { while (bodyContentReader.IsStartElement(XmlRpcProtocol.Param) && paramCounter < parameters.Length) { bodyContentReader.ReadStartElement(); if (bodyContentReader.IsStartElement(XmlRpcProtocol.Value)) { bodyContentReader.ReadStartElement(); bodyContentReader.MoveToContent(); if (bodyContentReader.NodeType == XmlNodeType.Text) { parameters[paramCounter] = bodyContentReader.ReadContentAs(_parameterInfo[paramCounter].ParameterType, null); } else { parameters[paramCounter] = XmlRpcDataContractSerializationHelper.Deserialize(bodyContentReader, _parameterInfo[paramCounter].ParameterType); } bodyContentReader.ReadEndElement(); } bodyContentReader.ReadEndElement(); bodyContentReader.MoveToContent(); paramCounter++; } } bodyContentReader.ReadEndElement(); bodyContentReader.Close(); }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { var s = request.GetReaderAtBodyContents(); Console.WriteLine("===custom message inspector and before send request is called"); return null; }
/// <summary cref="IClientMessageInspector.AfterReceiveReply" /> public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { // check for fault. if (reply.IsFault) { return; } // parse request parameters. object[] parameters = correlationState as object[]; if (parameters == null || parameters.Length != 3) { throw new InvalidOperationException("Cannot decode request because the IClientMessageInspector not configured properly."); } // extract request parameters. MessageVersion messageVersion = parameters[0] as MessageVersion; string action = parameters[1] as string; IServiceMessage request = parameters[2] as IServiceMessage; object encodeable = null; if (!reply.Properties.TryGetValue(MessageProperties.UnencodedBody, out encodeable)) { // extract binary encoded response from body. XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.MoveToStartElement("InvokeServiceResponse", Namespaces.OpcUaXsd); byte[] response = reader.ReadElementContentAsBase64(); // decode body. try { encodeable = BinaryDecoder.DecodeMessage(response, null, m_messageContext); } catch (Exception e) { ServiceResult error = ServiceResult.Create( e, StatusCodes.BadDecodingError, "Could not decoding incoming response message."); ServiceFault fault = new ServiceFault(); fault.ResponseHeader.RequestHandle = request.GetRequest().RequestHeader.RequestHandle; fault.ResponseHeader.Timestamp = DateTime.UtcNow; fault.ResponseHeader.ServiceResult = error.Code; StringTable stringTable = new StringTable(); fault.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( error, DiagnosticsMasks.NoInnerStatus, true, stringTable); fault.ResponseHeader.StringTable = stringTable.ToArray(); encodeable = fault; } } object unencodedBody = request.CreateResponse((IServiceResponse)encodeable); // create the unencoded reply message. Message unencodedReply = Message.CreateMessage( messageVersion, action + "Response", unencodedBody); unencodedReply.Headers.MessageId = reply.Headers.MessageId; unencodedReply.Headers.RelatesTo = reply.Headers.RelatesTo; unencodedReply.Properties.Add(MessageProperties.UnencodedBody, unencodedBody); // replace the incoming message. reply = unencodedReply; }
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { if (reply == null) { throw new ArgumentNullException("reply"); } if (correlationState != null && correlationState is string) { // if we have a JSONP callback then buffer the response, wrap it with the callback call and then re-create the response message string callback = (string)correlationState; XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.ReadStartElement(); string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64()); content = callback + "(" + content + ");"; using (Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(content))) { newreply.Properties.CopyProperties(reply.Properties); reply = newreply; // change response content type to text/javascript if the JSON (only done when wrapped in a callback) var replyProperties = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name]; replyProperties.Headers["Content-Type"] = replyProperties.Headers["Content-Type"].Replace("application/json", "text/javascript"); } } }