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

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Soll ich einen Statuscode zurückgeben oder eine Ausnahme in .Net Web Api 2 auslösen?

by Guest » 03 Jan 2025, 17:34

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

Top