У меня проблемы с возвратом правильного кода ошибки HTTP для "not found" в моем коде веб-API WCF.Вот мой метод API ...
[WebInvoke(Method = "GET", UriTemplate = "{id}")]
[RequireAuthorisation]
public Customer GetCustomer(int id)
{
var customer = Repository.Find(id);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return customer;
}
У меня также есть обработчик журнала ...
protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message)
{
if (exception != null)
{
var msg = "Request failed.";
_logger.Error(exception, msg);
}
message = new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError
};
return true;
}
Что происходит, я получаю следующее исключение ...
HttpResponseException
"The response message returned by the Response property of this exception should be immediately returned to the client. No further handling of the request message is required."
... который обрабатывает мой обработчик логов и меняет код статуса ответа на 500.
Итак, основываясь на чтении нескольких постов в блоге и ответов на SO, я перешел на этот...
if (customer == null)
{
WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
return null;
}
... но теперь это дает мне 200. Что явно не так.
Итак, как правильно это сделать?Кажется, что исключение HttpResponseException не работает, а код после выполняется.