 <pre><code>//由于调用 ProvideFault 时，客户端处于阻塞状态,不要在这里进行长时间的操作 public void ProvideFault(Exception error, MessageVersion version, ref Message msg) { //避免敏感信息泄漏,例如:数据库配置, error包含的错误信息应该记录到服务器的日志中,不能显示给客户端 // FaultException&lt;int&gt; e = new FaultException&lt;int&gt;(123, error.Message); DateTime now = DateTime.Now; time = now.ToString("yyyyMMddHHmmssfff", DateTimeFormatInfo.InvariantInfo);// "" + now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString(); string errorMsg = "服务内部错误_" + time; // FaultException fe = new FaultException(errorMsg); // MessageFault mf = fe.CreateMessageFault(); // msg = Message.CreateMessage(version, mf, fe.Action); //The fault to be returned msg = Message.CreateMessage(version, "", errorMsg, 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 msg.Properties.Add(WebBodyFormatMessageProperty.Name, wbf); //Modify response HttpResponseMessageProperty rmp = new HttpResponseMessageProperty(); // return custom error code, 400. rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError; rmp.StatusDescription = "Bad request"; //Mark the jsonerror and json content rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; rmp.Headers["jsonerror"] = "true"; //Add to fault msg.Properties.Add(HttpResponseMessageProperty.Name, rmp); } </code></pre>