0

I've seen many examples about use of HttpResponseException type in order to return a differents http status code through the raising of this exception.

However, all times I try to raise a HttpResponseException, client side I always receive 500 Internal server error regardless of my status code is different from that.

My API return an IEnumerable where T is a simple object and I'm using Net 6 version.

Sample Code

[HttpGet]
public IHttpActionResult Get()
{
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
    {
        Content = new StringContent("Could not find.."),
        ReasonPhrase = "Test not found"
    });

    return null;
}

Any idea?

mason
  • 31,774
  • 10
  • 77
  • 121
bit
  • 934
  • 1
  • 11
  • 32
  • In general, you shouldn't use exceptions for normal programming flow anyways. Now you're talking about an API and .NET, but you haven't specified what framework you're using: Web API 2 on ASP.NET framework on .NET Framework? Or are you using ASP.NET Core? Please edit the relevant code into your question and tag your question appropriately. Explain what status code you'd like to return as well. – mason Aug 04 '22 at 13:12
  • _"all times I try to raise a HttpResponseException"_ Can we see the code for this? – phuzi Aug 04 '22 at 13:24
  • I'm using .NET 6 as I've written on post. The code is very simple, now I edit my post. – bit Aug 04 '22 at 13:40
  • 1
    If you `throw` then an exception has occurred. This is not an exception, it's just a `NotFound` result – Charlieface Aug 04 '22 at 14:30
  • So all example I've already seen are wrong? Cos all of them execute thre new HttpResponseMessa(...) – bit Aug 04 '22 at 15:27

1 Answers1

1

For your specific example of a "not found" response, take a look at the NotFound helper method on ControllerBase which allows you to do something like this:

public ActionResult MyAPIEndpoint()
{
    return NotFound(new
    {
        ReasonPhrase = "Some message",
        SomeOtherField = "blah"
    });
}

Which will give you the following response when you query it: api response

If you wanted to return a code for which there isn't a helper, take a look at StatusCode which is also on ControllerBase, allowing you to do stuff like this:

public ActionResult ImATeapot()
{
    return StatusCode(418);
}

Querying this gives:

teapot

lee-m
  • 2,269
  • 17
  • 29
  • I've found an elegant solution through Filter: https://learn.microsoft.com/it-it/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0 – bit Aug 17 '22 at 15:58