Я реализую веб-службу RESTful с использованием WCF и WebHttpBinding. В настоящее время я работаю над логикой обработки ошибок, реализуя собственный обработчик ошибок (IErrorHandler); цель состоит в том, чтобы поймать любые неперехваченные исключения, вызванные операциями, а затем вернуть объект ошибки JSON (включая, например, код ошибки и сообщение об ошибке - например { "errorCode": 123, "errorMessage": "bla" }) назад пользователя браузера, а также HTTP-код, такой как BadRequest, InteralServerError или что-то в этом роде (ничего, кроме "ОК" ). Вот код, который я использую внутри метода ProvideFault моего обработчика ошибок:
fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
var rmp = new HttpResponseMessageProperty();
rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
rmp.Headers.Add(HttpRequestHeader.ContentType, "application/json");
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
- > Это возвращается с Content-Type: application/json, однако код состояния "OK" вместо "InternalServerError".
fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
var rmp = new HttpResponseMessageProperty();
rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
//rmp.Headers.Add(HttpRequestHeader.ContentType, "application/json");
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
- > Возвращается с правильным кодом состояния, однако тип содержимого теперь является XML.
fault = Message.CreateMessage(version, "", errorObject, 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;
- > Возвращается с правильным кодом состояния и правильным типом содержимого! Проблема в том, что тело http теперь имеет текст "Не удалось загрузить источник для: http://localhost:7000/bla.. 'вместо фактических данных JSON..
Любые идеи? Я рассматриваю возможность использования последнего подхода и просто придерживаюсь JSON в поле заголовка HTTP StatusMessage, а не в теле, но это выглядит не так хорошо?