Ich habe solche Beispiele gesehen
Code: Select all
public IHttpActionResult GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Ok(item);
}
Aber ich stelle mir auch vor, dass dies eine Option ist
Code: Select all
public IHttpActionResult GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
Gibt es einen Vorteil, eine Ausnahme auszulösen oder einfach eine NotFound-Instanz (IHttpActionResult-Instanz) zurückzugeben?
Ich weiß Es gibt Phasen in der Antwort-/Anforderungspipeline, in denen jedes dieser Ergebnisse verarbeitet werden kann, wie dies für das erste Beispiel
Code: Select all
public class NotFoundExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotFoundException)
{
// Do some custom stuff here ...
context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
}
...
GlobalConfiguration.Configuration.Filters.Add(
new ProductStore.NotFoundExceptionFilterAttribute());