Skip to main content

Best Practice : Validating Input Request .NET Core API

 We will learn multiple ways to validate input requests in .NET core Api.

Validating API input is crucial for ensuring data integrity, security, and the overall functionality of your application. When designing a RESTful API (or any kind of web service), it’s important to validate the inputs before processing them

We will implement validation request using Custom Middleware

  1. Custom Middleware for input validation

Additionally, we will also implement with below approaches

2 . Model Validation with Data Annotations

3. Validation Requests using Action Attributes

1. Custom Middleware for Validating Input

We will be creating custom middleware to add validation for all input requests and that will be centralize code for all api endpoints.

Above will be flow diagram for .NET core Api request processing and we added middleware which will work like if Validation fails then middleware will send response back to User.

Steps for implementations

a. Create RequestValidationMiddleware class

b. Inject RequestDelegate object in contructor : this will take care to pass request to next middleware in pipeline.

c. Add logic in InvokeAsync method which will take Httpcontext as input request and now we will have all data which input request should have.

d. Register middleware in Startup.cs.

Code below

Endpoint code

Testing

Input : Valid Data.

When we execute this request middleware will call and below code will execute: we can see we are getting JSON data which we are passing from user input.

we can add all required validations and sending back with 400 statuses if data is not good.

Testing with Invalid Data :

We are not passing name and getting validation error.

2. Model Validation with Data Annotations

One of the most common and clean ways to validate input in ASP.NET Core is using data annotations. This technique uses attributes to define validation rules on model properties.

Let’s have a code below, we are going to create user model and will add some validation attributes.

We have defined Range for Age, Emailaddresss and Name and mandatory.

Validation Code at API end point

We have used Modelstate which is defined on controller base class and it take care for all validations.

Testing: below is running screen of API and we have added valid input.

Negative scenario Testing.

a. I have removed name from input, now we should get error message as we made it required.

Error as expected.

b. Let’s make Age as out of range like 150.

Output

we can see we are getting expected validation messsage when we pass invalid input to API.

3. Validation Requests using Action Attributes

we have one problem in above approach, we have to add code to validate input inside controller action.

so if we have 100 of controllers then we need to add similar code on each endpoint or function which some time difficult to manage.

in this case we will create centralize place from where request get validate.

We are going to create Actionfilter class via below way and will validate all input data inside OnActionExecuting method.

Apply Attribute.

Testing

a. Invalid Email

Result. we can see this is working and getting validation message.

Conclusion:

We have learnt 3 approaches but best approaches will be custom middleware because by using middleware for validation, you can centralize all your validation logic in one place, making it easier to maintain and update.

Thanks

#coding, #bestpractice , #dotnetcore, #api

Comments

Popular posts from this blog

Design Application using Clean Architecture

  Clean Architecture , introduced by  Robert C. Martin   (Uncle Bob), aims to create systems that are: Independent of frameworks Testable Independent of UI Independent of database Independent of any external agency Clean Architecture emphasizes separating the concerns of different parts of the system and ensuring that each part has a clear responsibility. .NET clean architecture as a development approach, available in a layered form to reduce dependency. The architecture consists of several layers, each with a specific role and dependencies that flow in one direction: from the outer layers to the inner layers. Inner most Layer is independent to its outer layer, means inner most layer does not have any references, it builds and stand independently. Dependency Rule The core principle of Clean Architecture is the  Dependency Rule , which states that source code dependencies can only point inward.  This means: Nothing in inner circle can depend on anything in an out...

How to Earn online from Medium.com

  As freelancer I started writing on medium (Tech blogs) from  Aug 2024   but I was already writing tech blogs on c-sharpcorner.com “The purpose of this post is to encourage new writers by helping them understand how they can earn as freelancers.” “Medium is a great platform for writers. When I started writing, I had no idea that I would reach the $100 benchmark in just four months. Now, I’m feeling self-inspired, as it has become a valuable source of income as a freelancer.” AUG 2024 ( $0 ) It was just beginning, and I posted 4 articles and had only few views 455 and 165 reads. During this time, I was learning about medium rules for writers and partner program. It will take some time to understand over all process. SEP 2024 ($6) As I started writing and I was getting few cents on Aug 2024, I posted 8 more articles in SEP, and it was good month because my blogs were getting noticed and I started getting claps etc. “This month, I went from $0 to $6, which was an achievemen...

Fixing High CPU Usage in .NET Core using Parallelism

  We will fix problem occurs due to incorrect use Parallelism in .NET Core To increase application performance sometimes we use process task or work extensively in Parallel and that may lead performance issue. When we do code, we should understand our requirement very carefully along with hardware resources those we have. We should code like that there should be less CPU usage and server should work without issues. In .NET Core, when you’re using parallelism (like Parallel.For, Task.WhenAll, or Task.Run), you might encounter performance issues if the number of concurrent threads or tasks exceeds what your system can efficiently handle. A common issue is high CPU usage or resource contention, which can degrade overall performance, cause excessive context switching, and even lead to thread starvation or deadlocks. Non members can access from here Effective Parallelism Strategies to Mitigate High CPU Usage in .NET Core We will fix problem occurs due to incorrect use Parallelism in .NE...