Soll ich einen Statuscode zurückgeben oder eine Ausnahme in .Net Web Api 2 auslösen?C#

Ein Treffpunkt für C#-Programmierer
Guest
 Soll ich einen Statuscode zurückgeben oder eine Ausnahme in .Net Web Api 2 auslösen?

Post by Guest »

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());

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post