MediatR behaviors to validate API Resource existence
Tags: dotnet, cleancode, csharp, api
Published: 2018-09-12 18:07:25

---
title: MediatR behaviors to validate API Resource existence
published: true
tags: dotnet,clean-code,csharp,api
canonical_url: https://hackernoon.com/mediatr-behaviors-to-validate-api-resource-existence-f81182e8a36c
---

![](https://cdn-images-1.medium.com/max/475/1*UGlyWoUBAwLEzJFPlz8fmQ.png)<figcaption>MediatR logo borrowed from <a href="https://bit.ly/2N4Jz6S">https://bit.ly/2N4Jz6S</a></figcaption>

When building robust APIs it it really important with validation and descriptive error messages and status codes.

In this post I am going to show you how you can get rid of duplicated code in your Request Handlers by adding MediatR behaviors to take care of validation for resource existence.

[MediatR](https://github.com/jbogard/MediatR) is an in-process messaging library in .NET that supports requests/responses, commands, queries, events etc. Go check it out if you haven’t.

In MediatR there is something called behaviors which allow you to build your own pipeline for requests. I use them for cross cutting concerns such as logging and validation of requests parameters.

Recently when some endpoints were developed for a microservice I struggled with duplicated code in my Request Handlers that was necessary to have in place.

To give you an example lets start with a couple of API endpoints, and also the implementation of the Request Handlers with the duplicated code.

The endpoints in this example are:

PUT /groups/{id}

POST /groups/{id}/users

The controller:

{% gist https://gist.github.com/nengberg/aa8edabd668f9c1fd342cae074cba370 %}

Both endpoints need to verify that the id-parameter actually matches a given group to be able to update a group / add user to a group (in my example I’m using EF Core as persistence, but you can safely ignore that).

{% gist https://gist.github.com/nengberg/5692e4a55663ee73eadd4a078d0d488d %}

{% gist https://gist.github.com/nengberg/e5abb3f423eabf2ad6641baaef692a98 %}

As you can see there is an if-check for group existence in both the handlers.

How should we get rid of this duplication? Wouldn’t it be good to use some sort of “validation” here as a pre-step, so that the Request Handlers could look like this?

{% gist https://gist.github.com/nengberg/464941034a7783fa6d2da91798742a92 %}

{% gist https://gist.github.com/nengberg/89018964d8a5911cd88ed6303f0d0252 %}

Thank behaviors for that! Let’s introduce an interface that both the requests: UpdateGroupRequest and AddUserToGroupRequest implement.

{% gist https://gist.github.com/nengberg/705ef819afb0016e8ac2cfd31d496691 %}

Then create a behavior implementation class with generic constraint to the interface defined above so that the behavior only applies to requests implementing the IGroupRequest interface.

{% gist https://gist.github.com/nengberg/27a3ae3e8124e17f8847fbab587b3d2a %}

And a registration example using Autofac:

{% gist https://gist.github.com/nengberg/27931c0631f725a9827a2a0fcee61688 %}

Now we can rewrite our Request Handlers without the if statements, but still get the benefit of validation!

Lets imagine we now add a couple of more endpoints:

GET /groups/{id}

POST /groups/{id}/permissions

Add the IGroupRequest interface to your requests and you will get this feature out of the box. Pretty simple! I find this kind of approach really useful. What do you think?

We have to keep in mind that there are both some cons and pros to this approach. What I’ve found out is:

### Cons

- Multiple roundtrips if you have a database that you validate the existence against.
- Validation as a separate class which might confuse some of the developers

### Pros

- Cleaner code in the actual request handler
- No duplicated code scattered all over all Request Handlers that need to validate an entity’s existence

If you liked this post. You know what to do! 👏

* * *