Brett
Brett

Reputation: 2746

ASP.net Web API - Generic 404 handling

Is there a way to handle 404 (resource not found) generically, or do I have to write logic for each action? A simple example of what I am currently doing:

    //single-read
    public HttpResponseMessage Get(Guid guid)
    {
        School school = new School(guid);

        if (school == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
            //bonus-question: would it be better to instead: throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        //bonus-bonus-question: what is the benefit of using a typed response?
        return Request.CreateResponse<School>(HttpStatusCode.OK, school);
    }

If possible, I would like the "not found" logic to be handled elsewhere so that I didn't need to repeat those few lines of checking for each action. For example, I'd like it if it could be reduced to:

    //single-read
    public HttpResponseMessage Get(Guid guid)
    {
        School school = new School(guid);
        return Request.CreateResponse<School>(HttpStatusCode.OK, school);
    }

Upvotes: 1

Views: 242

Answers (1)

Ameen
Ameen

Reputation: 2586

You can implement an IActionFilter on your controller which will be called everytime an action is about to be executed and also when an action has finished execution. You can then perform your checking logic there. See documentation. You would annotate the controller class itself with your filter and it would be called for all actions.

In terms of the error handling, if you don't throw an exception, then you won't pay the cost of exceptions (which I'd like to pretend to be negligible), but more importantly, you won't allow any exception handlers to kick in and that may be something you actually want. Take a look at IExceptionFilter for example that gets called whenever an exception is thrown. If there is a part of your application that relies on that (for example logging errors), that component won't know that there was an error when you don't throw an exception, so it's a design call.

Upvotes: 1

Related Questions