ASP.NET Core – How to manually validate a model in a controller

Manually validating a model can mean a few different things. It depends on what you’re trying to do exactly. Are you trying to validate a model object against its validation attributes? Use TryValidateModel(). Are you trying to do validation logic manually (instead of using validation attributes)? You can add errors to ModelState in that case. … Read more

ASP.NET Core – API model validation attributes

It’s always a good idea to validate data coming into your web API. There are two steps you can do to guard against invalid data: Here’s an example of using model validation attributes: When a request comes in, the framework does two things: Let’s say you send a request with invalid data (boxOfficeMillions is outside … Read more

ASP.NET Core – How to receive a file in a web API request

When the client posts a file in a multipart/form-data request, it’s loaded into an IFormFile object. This contains file information (such as the file name) and exposes the file content as a stream. This allows you to save the file content or process it however you want to. You can access the IFormFile object through … Read more

ASP.NET Core – How to return a 500 response

The simplest way to return a 500 response is to use the Problem() helper method, like this: This method returns an ObjectResult with status code 500 and a generic error message, which gets serialized to JSON and returned in the response body. The response looks like this: The ControllerBase class has many helper methods like … Read more

ASP.NET Core – How to unit test an action filter

To unit test an action filter, you have to pass in an action filter context object (which requires a lot of setup). Action filter methods are void, so you have to verify the behavior by inspecting the context object (or dependencies, like a logger, if you are injecting those). Here’s an example of doing the … Read more

Add a custom action filter in ASP.NET Core

Action filters allow you to look at requests right before they are routed to an action method (and responses right after they are returned from the action method). The simplest way to add your own action filter in ASP.NET Core is to subclass ActionFilterAttribute and then override the appropriate methods depending on if you want … Read more

ASP.NET Core – How to unit test an ApiController

The key to unit testing an ApiController class is to mock out all of its dependencies, including the controller’s HttpContext property, like this: If the controller method you’re testing uses anything from the HttpContext, then you’ll want to swap in your own value. Otherwise HttpContext will be null and you’ll get a NullReferenceException. Fortunately Microsoft … Read more