Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.
- Part 1 - Customizing auto-generated documentation
- Part 2 - HTTP Response Codes
- Part 3 - HTTP Error Codes from Exceptions (this article)
- Part 4 - OData URL Query Options
- Part 5 - DTO Transformations and Automapper
- Part 6 - Testing with EF Rollbacks across HTTP
In the last post, we looked at how you can specify HTTP Response codes to return from your API controller when everything is working properly. However, sometimes a problem will occur deep inside your code. Continuing down the REST path, when problems occur, you should use the semantics of HTTP by returning an HTTP status code that reflects the error. When problems occur in your code, exceptions are typically thrown. This week we will be looking at how we can specify the HTTP Response code and content to return depending on the exception that is thrown.
Feb 10, 2016 Update - Fixed bug in second code block
This is a matter of style, but the first thing that I like to do is to create a custom exception, so that I know that what I’m doing will only apply when I specifically raise my custom exception.