WEB API 2 filters on .net 5 to handle Exceptions

Hello my dear developers!

How do you feel today?

I’ve seen many times web API’s controller’s methods with ActionResult as return types. On these methods there are lots of defensive code so an appropriate status response can be generated. A neat trick to avoid crowding your controller methods handling exceptions is to user filters.

Filters are part of asp.net core pipeline, a middleware to handle recurring situation.

Filters in ASP.NET Core | Microsoft Docs

I based my solution on the following article since is a simple explanation (in net core 2.1 though):

Using ExceptionFilter for exception handling in AspNet Core Web API – Janak’s blog

I basically throw a domain exception an handle at in my own ExceptionFilter:

DoTasksBeforeReady/ExceptionFilter.cs at main · ambsenyestudi/DoTasksBeforeReady (github.com)

You just need to add it at Startup.cs on ConfigureServices and you are done

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(config=> {
        config.Filters.Add(typeof(ExceptionFilter));
    });
    ...
}

Happy coding and remember…there is life beyond coding🙂

Testing with http client

Hello my dear developers!

How do you feel today?

I was trying to mock httpclient o use some sort of trick to test it. Found nothing and then decided to write my own HttpMessageHandler class.

While trying to look at the docs to be able to pass a factory function at constructor, I found this very interesting article of a guy that already did it.

https://dev.to/n_develop/mocking-the-httpclient-in-net-core-with-nsubstitute-k4j

I hope you enjoy this article as much as I did.

Happy coding and remember…there is life beyond coding🙂

Open API (Swagger) and fluent validation

Hello my dear developers!

How do you feel today?

Continuing with the spirit of validating models easily on API started at:

https://afreixasblog.wordpress.com/2019/11/01/stop-validations-in-code-and-use-dataannotation/

I found this awesome article that uses fluent api on swagger to document your model

https://www.anexinet.com/blog/asp-net-core-fluentvalidation-swagger/

I hope you enjoy this article as much as I did.

Happy coding and remember…there is life beyond coding🙂