ApiController Validation in .Net Core 2.1/2.2 – Unit Testing

One of the additions in .NET Core 2.1 was the introduction of the [ApiController] attribute which could be applied at Controller level to validate the Model State, removing a lot of boilerplate code around the system. (NB. .NET Core 2.2 introduced the ability to set this at assembly level, e.g.

[assembly: ApiController]
namespace WebApp

This can be applied on any class, but I’ve choosen Startup.cs as a fairly obvious place for the configuration of most things.

Before .NET Core 2.1, a lot of code would have looked like the following:

public async Task<IActionResult> ActionToPerform(InputModel inputModel)
   if (!ModelState.IsValid)
      return BadRequest();

This boilerplate code is likely to be scattered the code base.

With this code in place, the invalid state of the model can tested using Unit Tests as follows (NB. The error must be manually set, as the model binding won’t happen without the middleware pipeline)

var controller = new StudentController();

// force model state to be invalid.
controller.ModelState.AddModelError(string.Empty, "Test Error");

Assert.IsFalse(controller.ModelState.IsValid, "Model state has remained valid.");

// Test for BadRequest being returned
Var result = await controller.ActionToPerform(model);
BadRequestResult badRequestResult = result as BadRequestResult;

Assert.IsNotNull(badRequestResult, "Wrong type returned.");

With this test in place, and hopefully passing, now comes the opportunity to introduce the ApiController attribute. In theory that means that the boilerplate code can be removed, and the pass will continue to pass.

Unfortunately that’s not the case. As per the binding on the model state, I’m assuming this happens elsewhere in the pipeline. Indeed it can be proved to be working outside of the Unit Tests by using Postman to trigger a request and see a BadRequest (400) be returned – provided an invalid object is supplied).

As such the Unit Test needs to change to check for the presence of ApiController – either on the Controller itself, or at Assembly level, depending on where its been declared. Here is the test for assembly level, on the StartUp class:

var customAttributes = typeof(Startup).Assembly.GetCustomAttributes(true);

var entry = customAttributes.FirstOrDefault(a => a.GetType().Name == "ApiControllerAttribute");








Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s