C# – Manually validate objects that have model validation attributes

You can use the Validator utility class to do manual attribute-based validation on any object, in any project type (as opposed to doing automatic model validation in ASP.NET). To do this, add model validation attributes to your class properties, then create an object and populate it (aka binding), and finally execute manual validation with the … Read more

ASP.NET Core – How to get request headers

There are two ways to get request headers: When a request comes in, the framework loads request headers into the Request.Headers dictionary. You can use this just like any other dictionary. Here’s an example of using TryGetValue() to check if a request header exists and get its value: Note: To just check if a header … Read more

ASP.NET Core – Create a custom model validation attribute

There are many built-in model validation attributes available – such as [Required] and [Range] – which you can use to handle most validation scenarios. When these aren’t sufficient, you can create a custom validation attribute with your own validation logic. I’ll show an example of how to do that. 1 – Subclass ValidationAttribute and implement … 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 – Getting query string values

The ASP.NET Core framework automatically parses query strings (i.e. ?name=Dune&year=2021) into HttpContext.Request.Query and maps the query string values to parameters in the action method (if you’ve added them). You can get the mapped query string values by adding action parameters, like this: Or you can use HttpContext.Request.Query directly (which is useful in many scenarios): This … Read more

ASP.NET Core – Get posted form data in an API Controller

To get posted form data in an API Controller (using the [ApiController] attribute) in ASP.NET Core, use parameters with the [FromForm] attribute. Now send a request with form data to this endpoint to see it work. The request would look like this: The form data is a string of key-value pairs (ex: location=United+States). The framework … Read more

C# – Using reflection to get properties

You can get a list of a type’s properties using reflection, like this: Note: If you have an object, use movie.GetType().GetProperties() instead. This outputs the following: When you use GetProperties(), it returns a list of PropertyInfo objects. This gives you access the property’s definition (name, type, etc…) and allows you to get and modify its … Read more