Conventions useful for creating an ASP.NET Core based REST API on top of a domain model.
An Exception Filter for converting supported Exceptions to IActionResults, automatically setting the type, status code, and message, as appropriate. The following conversions are performed by default:
- Base DomainException to BadRequest (HTTP 400)
- UnauthorizedException to Unauthorized (HTTP 401)
- EntityNotFoundException to NotFound (HTTP 404)
The DomainExceptionFilter
should be added to the collection of filters on the MvcOptions configuration for your application. For example, if MVC Core is added to your service collection using a custom configurer
services.AddMvcCore(options => options.ConfigureMvc())
then simply add the DomainExceptionFilter
to the collection of filters
internal static class MvcConfigurer
{
public static void ConfigureMvc(this MvcOptions options)
{
...
options.Filters.Add(new DomainExceptionFilter());
}
}
Since DomainException
is extensible for any domain-specific error, DomainExceptionFilter
can be extended to support custom Exception to Result mappings. Simply pass a Func<DomainException, ErrorResponse, IActionResult>
to the constructor, such as
new DomainExceptionFilter((exception, response) => exception is TeapotException ? new TeapotResult() : null) // 418
Note that all custom mappings are handled after EntityNotFoundException
s and UnauthorizedException
s.