void BuildHttpResponseMessage( object faultDetails, string action, HttpStatusCode httpStatusCode, ref Message fault) { if (fault == null) { throw new ArgumentNullException(nameof(fault)); } var responseMessageProperty = new HttpResponseMessageProperty(); responseMessageProperty.StatusCode = httpStatusCode; responseMessageProperty.StatusDescription = Fault.GetHttpStatusDescription(responseMessageProperty.StatusCode); var webFormat = GetWebContentFormat(); if (webFormat == WebContentFormat.Json) { // set the status code, description and content type in the response header: responseMessageProperty.Headers[HttpResponseHeader.ContentType] = "application/json"; // build a new fault message. In the body use a JSON serializer to serialize the fault details. fault = Message.CreateMessage( fault.Version, action, faultDetails, new DataContractJsonSerializer(faultDetails.GetType())); fault.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty); fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(webFormat)); return; } if (webFormat == WebContentFormat.Xml) { // set the status code, description and content type in the response header: responseMessageProperty.Headers[HttpResponseHeader.ContentType] = "application/xml"; // build a new fault message. In the body use a data contract (XML) serializer to serialize the fault details. fault = Message.CreateMessage( fault.Version, action, faultDetails, new DataContractSerializer(faultDetails.GetType())); fault.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty); fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(webFormat)); return; } else { // just dump the message as text responseMessageProperty.Headers[HttpResponseHeader.ContentType] = "text/plain"; fault = Message.CreateMessage( fault.Version, action, faultDetails.DumpString()); fault.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty); fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw)); } }