Beispiel #1
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            // Tell WCF to use JSON encoding rather than default XML
            var webBodyFormatProperty = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            var responseProperty      = new HttpResponseMessageProperty();

            responseProperty.Headers.Add(HttpResponseHeader.ContentType, "application/json");

            if (error is FaultException)
            {
                // Extract the FaultContract object from the exception object.
                var detail = error.GetType().GetProperty("Detail").GetGetMethod().Invoke(error, null);

                // Return custom error http response.
                responseProperty.StatusCode = System.Net.HttpStatusCode.Unauthorized;

                // Create a fault message containing our FaultContract object
                fault = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(detail.GetType()));
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, webBodyFormatProperty);
                fault.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
            }
            else
            {
                // Return custom error http response.
                responseProperty.StatusCode = System.Net.HttpStatusCode.InternalServerError;

                var detail = error.Message;

                fault = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(typeof(string)));
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, webBodyFormatProperty);
                fault.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
            }
        }
        private void CreateJsonErrorMessage(Exception error, MessageVersion version, ref Message fault, HttpStatusCode statusCode)
        {
            // Create message
            var jsonError = new ExposedFaultContract
            {
                Message = error.Message,
                ErrorId = DateTime.Now.ToUnixTime()
            };

            fault = Message.CreateMessage(version, "", jsonError, new DataContractJsonSerializer(typeof(ExposedFaultContract)));

            // Tell WCF to use JSON encoding rather than default XML
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            // Modify response
            var rmp = new HttpResponseMessageProperty
            {
                StatusCode        = statusCode,
                StatusDescription = "Bad Request",
            };

            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
        void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            ServiceDiagnostics.ReportUnhandledException(error, HttpContext.Current);
            string text  = HttpContext.Current.Request.QueryString["$format"];
            string text2 = HttpContext.Current.Request.Headers["Accept"];
            XmlObjectSerializer          serializer;
            WebBodyFormatMessageProperty property;

            if ((text != null && text.Equals("json", StringComparison.InvariantCultureIgnoreCase)) || (text2 != null && text2.Equals("application/json", StringComparison.InvariantCultureIgnoreCase)))
            {
                serializer = new DataContractJsonSerializer(typeof(ServiceFault));
                property   = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            }
            else
            {
                serializer = new DataContractSerializer(typeof(ServiceFault));
                property   = new WebBodyFormatMessageProperty(WebContentFormat.Xml);
            }
            fault = Message.CreateMessage(version, string.Empty, new ServiceFault(string.Empty, error), serializer);
            fault.Properties.Add("WebBodyFormatMessageProperty", property);
            HttpResponseMessageProperty httpResponseMessageProperty = new HttpResponseMessageProperty();
            DataServiceException        ex = error as DataServiceException;

            if (ex != null)
            {
                httpResponseMessageProperty.StatusCode = (HttpStatusCode)ex.StatusCode;
            }
            else
            {
                httpResponseMessageProperty.StatusCode = HttpStatusCode.InternalServerError;
            }
            fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponseMessageProperty);
        }
Beispiel #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <param name="parameters"></param>
        public void DeserializeRequest(Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty))
            {
                throw new InvalidOperationException("Incoming message cannot be null.");
            }

            WebBodyFormatMessageProperty bodyMsg = bodyFormatProperty as WebBodyFormatMessageProperty;

            if (bodyMsg == null)
            {
                throw new InvalidCastException("The type of body message must be WebBodyFormatMessageProperty.");
            }

            if (bodyMsg.Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("The body message type must be equals to WebContentFormat.Raw.");
            }

            ////
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement(BinaryRawBodyWriter.DefaultRootName);

            this.DecodeParameters(bodyReader.ReadContentAsBase64(), parameters);
        }
Beispiel #5
0
        ///
        /// Apply Json settings to the message
        ///
        protected virtual void ApplyJsonSettings(ref Message fault)
        {
            // Use JSON encoding
            var jsonFormatting = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);
        }
        public void ProvideFault(System.Exception error, MessageVersion version, ref Message fault)
        {
            //The fault to be returned
            fault = Message.CreateMessage(version, "", error.ToString(), new DataContractJsonSerializer(typeof(string)));

            // tell WCF to use JSON encoding rather than default XML
            WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            // Add the formatter to the fault
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            //Modify response
            HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

            // return custom error code, 500.
            rmp.StatusCode        = System.Net.HttpStatusCode.InternalServerError;
            rmp.StatusDescription = "InternalServerError";

            //Mark the jsonerror and json content
            rmp.Headers[HttpResponseHeader.ContentType]     = "application/json";
            rmp.Headers[HttpResponseHeader.ContentEncoding] = "utf-8";

            //Add to msg
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
        Stream GetStreamFromMessage(Message message, bool isRequest)
        {
            object prop;

            message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop);
            WebBodyFormatMessageProperty formatProperty = (prop as WebBodyFormatMessageProperty);

            if (formatProperty == null)
            {
                // GET and DELETE do not go through the encoder
                if (IsEmptyMessage(message))
                {
                    return(new MemoryStream());
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.MessageFormatPropertyNotFound, this.operationName, this.contractName, this.contractNs)));
                }
            }
            if (formatProperty.Format != WebContentFormat.Raw)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.InvalidHttpMessageFormat, this.operationName, this.contractName, this.contractNs, formatProperty.Format, WebContentFormat.Raw)));
            }
            return(new StreamFormatter.MessageBodyStream(message, null, null, HttpStreamMessage.StreamElementName, string.Empty, isRequest));
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error is FaultException)
            {
                // extract the our FaultContract object from the exception object.
                var detail = error.GetType().GetProperty("Detail").GetGetMethod().Invoke(error, null);
                // create a fault message containing our FaultContract object
                fault = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(detail.GetType()));
                // tell WCF to use JSON encoding rather than default XML
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

                // return custom error code.
                var rmp = new HttpResponseMessageProperty();
                rmp.StatusCode = System.Net.HttpStatusCode.BadRequest;
                // put appropraite description here..
                rmp.StatusDescription = "See fault object for more information.";
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
            else
            {
                fault = Message.CreateMessage(version, "", "An non-fault exception is occured.",
                                              new DataContractJsonSerializer(typeof(string)));
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
                // return custom error code.
                var rmp = new HttpResponseMessageProperty();
                rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                // put appropraite description here..
                rmp.StatusDescription = "Uknown exception…";
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
        }
Beispiel #9
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
        {
            ErrorInfo model = new ErrorInfo()
            {
                Message = error.Message
            };

            //添加将要返回的异常信息
            msg = Message.CreateMessage(version, string.Empty, model, new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ErrorInfo)));

            //告诉WCF使用JSON编码而不是默认的XML
            WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            //添加格式化程序故障。
            msg.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            //修改响应
            //HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

            // 返回自定义错误码, 500.
            //rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;

            //rmp.StatusDescription = "Bad request";

            ////Headers写入jsonerror和JSON内容( Content-Type 标头,指定伴随正文数据的 MIME 类型。)
            //rmp.Headers[System.Net.HttpResponseHeader.ContentType] = "application/json";
            //rmp.Headers[System.Net.HttpResponseHeader.ContentEncoding] = "utf-8";
            ////rmp.Headers["jsonerror"] = "true";

            ////添加到故障
            //msg.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (WebOperationContext.Current?.IncomingRequest.Accept != "application/json")
            {
                return;
            }

            // Create message
            var jsonError = new JsonErrorDetails
            {
                Message       = error.Message,
                ExceptionType = error.GetType().FullName
            };

            fault = Message.CreateMessage(version, "", jsonError,
                                          new DataContractJsonSerializer(typeof(JsonErrorDetails)));

            // Tell WCF to use JSON encoding rather than default XML
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            // Modify response
            var rmp = new HttpResponseMessageProperty
            {
                StatusCode        = HttpStatusCode.BadRequest,
                StatusDescription = "Bad Request",
            };

            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
Beispiel #11
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            Result model;

            if (error.GetType() == typeof(ApiException))
            {
                ApiException apiException = error as ApiException;
                model = new Result(apiException.Code, error.Message);
            }
            else
            {
                model = new Result(ApiResultEnum.UncaughtException, error.Message);
            }

            //添加将要返回的异常信息
            fault = Message.CreateMessage(version, "", model, new DataContractJsonSerializer(typeof(Result)));

            //告诉WCF使用JSON编码而不是默认的XML
            WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            //修改响应
            HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

            rmp.StatusCode = HttpStatusCode.OK;
            rmp.Headers[HttpResponseHeader.ContentType]     = "application/json";
            rmp.Headers[HttpResponseHeader.ContentEncoding] = "utf-8";
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
Beispiel #12
0
        public void ProvideFault(System.Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message message)
        {
            var fault = new Fault();

            if (error is FaultException)
            {
                // extract the our FaultContract object from the exception object.
                var detail = error.GetType().GetProperty("Detail").GetGetMethod().Invoke(error, null);

                // create a fault message containing our FaultContract object
                message = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(detail.GetType()));

                // tell WCF to use JSON encoding rather than default XML
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

                message.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

                // return custom error code.
                var rmp = new HttpResponseMessageProperty();
                rmp.StatusCode = System.Net.HttpStatusCode.BadRequest;

                // put appropraite description here..
                rmp.StatusDescription = "See fault object for more information.";

                message.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
            else if (error is SerializationException)
            {
                fault.Error = error.Message;
                fault.Error = "Could not decode request: JSON parsing failed";
                toJson(fault, ref message);
            }
        }
        public void Members()
        {
            WebBodyFormatMessageProperty p = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            Assert.AreEqual("WebBodyFormatMessageProperty", WebBodyFormatMessageProperty.Name, "#1");
            Assert.AreEqual(WebContentFormat.Json, p.Format, "#2");
            Assert.AreEqual("WebBodyFormatMessageProperty: WebContentFormat=Json", p.ToString(), "#3");
        }
Beispiel #14
0
            public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
            {
                HttpResponseMessageProperty responseProperty;

                if (fault == null)
                {
                    FaultCode code = new FaultCode(FaultCodeConstants.Codes.InternalServiceFault, FaultCodeConstants.Namespaces.NetDispatch);
                    code = FaultCode.CreateReceiverFaultCode(code);
                    string action = FaultCodeConstants.Actions.NetDispatcher;

                    MessageFault innerFault;
                    innerFault = MessageFault.CreateFault(code, new FaultReason(error.Message, CultureInfo.CurrentCulture), new ExceptionDetail(error));
                    fault      = Message.CreateMessage(version, action, new JsonFaultBodyWriter(innerFault, this.includeExceptionDetailInFaults));

                    responseProperty = new HttpResponseMessageProperty();
                    fault.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
                }
                else
                {
                    MessageFault innerFault = MessageFault.CreateFault(fault, TransportDefaults.MaxFaultSize);
                    Message      newMessage = Message.CreateMessage(version, fault.Headers.Action, new JsonFaultBodyWriter(innerFault, this.includeExceptionDetailInFaults));
                    newMessage.Headers.To = fault.Headers.To;
                    newMessage.Properties.CopyProperties(fault.Properties);

                    object property = null;
                    if (newMessage.Properties.TryGetValue(HttpResponseMessageProperty.Name, out property))
                    {
                        responseProperty = (HttpResponseMessageProperty)property;
                    }
                    else
                    {
                        responseProperty = new HttpResponseMessageProperty();
                        newMessage.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
                    }

                    fault.Close();
                    fault = newMessage;
                }
                responseProperty.Headers.Add(HttpResponseHeader.ContentType, outgoingContentType);
                responseProperty.Headers.Add(JsonGlobals.jsonerrorString, JsonGlobals.trueString);
                responseProperty.StatusCode = System.Net.HttpStatusCode.InternalServerError;

                object bodyFormatPropertyObject;

                if (fault.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatPropertyObject))
                {
                    WebBodyFormatMessageProperty bodyFormatProperty = bodyFormatPropertyObject as WebBodyFormatMessageProperty;
                    if ((bodyFormatProperty == null) ||
                        (bodyFormatProperty.Format != WebContentFormat.Json))
                    {
                        fault.Properties[WebBodyFormatMessageProperty.Name] = WebBodyFormatMessageProperty.JsonProperty;
                    }
                }
                else
                {
                    fault.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
                }
            }
Beispiel #15
0
            public virtual Message SerializeRequest(MessageVersion messageVersion, object [] parameters)
            {
                if (parameters == null)
                {
                    throw new ArgumentNullException("parameters");
                }
                CheckMessageVersion(messageVersion);

                var c = new Dictionary <string, string> ();

                MessageDescription md = GetMessageDescription(MessageDirection.Input);

                if (parameters.Length != md.Body.Parts.Count)
                {
                    throw new ArgumentException("Parameter array length does not match the number of message body parts");
                }

                for (int i = 0; i < parameters.Length; i++)
                {
                    var    p    = md.Body.Parts [i];
                    string name = p.Name.ToUpper(CultureInfo.InvariantCulture);
                    if (UriTemplate.PathSegmentVariableNames.Contains(name) ||
                        UriTemplate.QueryValueVariableNames.Contains(name))
                    {
                        c.Add(name, parameters [i] != null ? Converter.ConvertValueToString(parameters [i], parameters [i].GetType()) : null);
                    }
                    else
                    {
                        // FIXME: bind as a message part
                        throw new NotImplementedException(String.Format("parameter {0} is not contained in the URI template {1} {2} {3}", p.Name, UriTemplate, UriTemplate.PathSegmentVariableNames.Count, UriTemplate.QueryValueVariableNames.Count));
                    }
                }

                Uri to = UriTemplate.BindByName(Endpoint.Address.Uri, c);

                Message ret = Message.CreateMessage(messageVersion, (string)null);

                ret.Headers.To = to;

                var hp = new HttpRequestMessageProperty();

                hp.Method = Info.Method;

#if !NET_2_1
                if (WebOperationContext.Current != null)
                {
                    WebOperationContext.Current.OutgoingRequest.Apply(hp);
                }
#endif
                // FIXME: set hp.SuppressEntityBody for some cases.
                ret.Properties.Add(HttpRequestMessageProperty.Name, hp);

                var wp = new WebBodyFormatMessageProperty(ToContentFormat(Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat));
                ret.Properties.Add(WebBodyFormatMessageProperty.Name, wp);

                return(ret);
            }
Beispiel #16
0
 private static WebContentFormat GetMessageContentFormat(ref Message message)
 {
     //WebContentFormat w = WebContentFormat.Default;
     if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
     {
         WebBodyFormatMessageProperty v = (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name];
         return(v.Format);
     }
     return(WebContentFormat.Default);
 }
Beispiel #17
0
        /// <summary>
        /// Get the message's classified format
        /// </summary>
        private WebContentFormat GetContentFormat(Message message)
        {
            WebContentFormat retVal = WebContentFormat.Default;

            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
            {
                WebBodyFormatMessageProperty propertyValue = message.Properties[WebBodyFormatMessageProperty.Name] as WebBodyFormatMessageProperty;
                retVal = propertyValue.Format;
            }
            return(retVal);
        }
        private WebContentFormat GetMessageContentFormat(Message message)
        {
            WebContentFormat format = WebContentFormat.Default;

            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
            {
                WebBodyFormatMessageProperty bodyFormat = (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name];
                format = bodyFormat.Format;
            }

            return(format);
        }
        internal static bool TryGetEncodingFormat(Message message, out WebContentFormat format)
        {
            object prop;

            message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop);
            WebBodyFormatMessageProperty formatProperty = prop as WebBodyFormatMessageProperty;

            if (formatProperty == null)
            {
                format = WebContentFormat.Default;
                return(false);
            }
            format = formatProperty.Format;
            return(true);
        }
Beispiel #20
0
        public object DeserializeReply(Message message, object[] parameters)
        {
            object prop;

            if (message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop))
            {
                WebBodyFormatMessageProperty format = (WebBodyFormatMessageProperty)prop;
                if (format.Format == WebContentFormat.Json)
                {
                    return(this.jsonFormatter.DeserializeReply(message, parameters));
                }
            }

            return(this.xmlFormatter.DeserializeReply(message, parameters));
        }
Beispiel #21
0
        public void ProvideFault(Exception exception, MessageVersion version, ref Message fault)
        {
            fault = GetJsonFaultMessage(version, exception);

            var jsonFormatting = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);

            var httpResponse = new HttpResponseMessageProperty
            {
                StatusCode        = HttpStatusCode.BadRequest,
                StatusDescription = "Bad Request"
            };

            fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
        }
    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var fd = new JsonFaultDetail();

        fd.Message = error.Message;
        fault      = Message.CreateMessage(version, string.Empty, fd, new DataContractJsonSerializer(fd.GetType()));
        var jsonFormatting = new WebBodyFormatMessageProperty(WebContentFormat.Json);

        fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);
        var httpResponse = new HttpResponseMessageProperty()
        {
            StatusCode = HttpStatusCode.InternalServerError,
        };

        fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
    }
        /// <summary>
        /// Providing error message to client side
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="version"></param>
        /// <param name="fault"></param>
        public void ProvideFault(Exception ex, MessageVersion version, ref Message fault)
        {
            var errorMessage = new ErrorMessage()
            {
                Message = "Server error encountered. For more info contact to administrator",
            };

            fault = Message.CreateMessage(version, "", errorMessage, new DataContractJsonSerializer(typeof(ErrorMessage)));
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
            var response = WebOperationContext.Current.OutgoingResponse;

            response.ContentType = "application/json";
            response.StatusCode  = HttpStatusCode.InternalServerError;
        }
Beispiel #24
0
        /// <summary>
        /// Enables the creation of a custom <see cref="FaultException" /> that is returned from an exception in the course of a service method.
        /// </summary>
        /// <param name="error">The <see cref="Exception" /> object thrown in the course of the service operation.</param>
        /// <param name="version">The SOAP version of the message.</param>
        /// <param name="fault">The <see cref="Message" /> object that is returned to the client, or service, in the duplex case.</param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            fault = Message.CreateMessage(version, "", new JsonFault(error), new DataContractJsonSerializer(typeof(JsonFault)));

            WebBodyFormatMessageProperty jsonFormatting = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);

            HttpResponseMessageProperty httpResponse = new HttpResponseMessageProperty
            {
                StatusCode        = HttpStatusCode.InternalServerError,
                StatusDescription = error.Message,
            };

            fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
        }
Beispiel #25
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error == null || version == null)
            {
                return;
            }

            fault = Message.CreateMessage(version, "", new ErrorMessage(error), new DataContractJsonSerializer(typeof(ErrorMessage)));
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            var response = WebOperationContext.Current.OutgoingResponse;

            response.ContentType = "application/json";
            response.StatusCode  = HttpStatusCode.InternalServerError;
        }
 protected override void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest)
 {
     if (message != null)
     {
         object prop;
         message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop);
         WebBodyFormatMessageProperty formatProperty = (prop as WebBodyFormatMessageProperty);
         if (formatProperty == null)
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.MessageFormatPropertyNotFound2, this.OperationName)));
         }
         if (formatProperty.Format != WebContentFormat.Json)
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.InvalidHttpMessageFormat3, this.OperationName, formatProperty.Format, WebContentFormat.Json)));
         }
     }
     base.GetHeadersFromMessage(message, messageDescription, parameters, isRequest);
 }
Beispiel #27
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var response = new ErrorResponse
            {
                Type       = error.GetType().FullName,
                Message    = error.Message,
                StackTrace = error.StackTrace
            };

            fault = Message.CreateMessage(version, "", response, new DataContractJsonSerializer(typeof(ErrorResponse)));
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            var outgoingResponse = WebOperationContext.Current.OutgoingResponse;

            outgoingResponse.ContentType = "application/json";
            outgoingResponse.StatusCode  = HttpStatusCode.InternalServerError;
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (fault == null)
            {
                throw new ArgumentNullException("fault");
            }
            var ex = new GeneralErrorFault {
                Message = error.Message
            };

            fault = Message.CreateMessage(MessageVersion.None, "", ex, new DataContractJsonSerializer(ex.GetType()));
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
            if (WebOperationContext.Current == null)
            {
                return;
            }
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
            WebOperationContext.Current.OutgoingResponse.StatusCode  = HttpStatusCode.InternalServerError;
        }
        private static Message Serialize(object obj)
        {
            Message message;

            using (var stream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize(stream, obj);
                message = Message.CreateMessage(MessageVersion, Action, new StreamBodyWriter(stream.ToArray()));
            }

            var contentType = "application/octet-stream";
            var httpResponseMessageProperty = new HttpResponseMessageProperty();

            httpResponseMessageProperty.Headers.Add(HttpResponseHeader.ContentType, contentType);
            var webBodyFormatMessageProperty = new WebBodyFormatMessageProperty(WebContentFormat.Raw);

            message.Properties[HttpResponseMessageProperty.Name]  = httpResponseMessageProperty;
            message.Properties[WebBodyFormatMessageProperty.Name] = webBodyFormatMessageProperty;

            return(message);
        }
 protected override void ValidateMessageFormatProperty(Message message)
 {
     if (this.useJsonFormat)
     {
         // useJsonFormat is always false in the green bits
         object prop;
         message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop);
         WebBodyFormatMessageProperty formatProperty = (prop as WebBodyFormatMessageProperty);
         if (formatProperty == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.MessageFormatPropertyNotFound, this.OperationName, this.ContractName, this.ContractNs)));
         }
         if (formatProperty.Format != WebContentFormat.Json)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.InvalidHttpMessageFormat, this.OperationName, this.ContractName, this.ContractNs, formatProperty.Format, WebContentFormat.Json)));
         }
     }
     else
     {
         base.ValidateMessageFormatProperty(message);
     }
 }