-
Notifications
You must be signed in to change notification settings - Fork 0
Custom Validate Model Attribute
In ASP.NET Core, we can improve the maintainability and cleanliness of our controller methods by using custom action filters for model validation. Instead of checking ModelState.IsValid in each controller action, a custom action filter centralizes the logic, reducing redundancy and keeping controller methods clean.
Organize your project by creating a dedicated folder for action filters.
- Right-click on the project.
- Add a new folder named
CustomActionFilters.
Create a new class inside the CustomActionFilters folder.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace YourNamespace.CustomActionFilters
{
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
}
-
ActionFilterAttribute: Provides a base class for custom action filters. -
OnActionExecuting: Executes before the controller action method runs. -
BadRequestObjectResult: Returns a 400 Bad Request response if the model validation fails.
Decorate controller actions with the ValidateModelAttribute to enable validation.
[HttpPost]
public IActionResult CreateRegion([FromBody] AddRegionRequestDTO request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Controller logic...
return Ok();
}
[HttpPost]
[ValidateModel]
public IActionResult CreateRegion([FromBody] AddRegionRequestDTO request)
{
// Controller logic...
return Ok();
}
- Replace repetitive
ModelState.IsValidchecks with the[ValidateModel]attribute.
You can apply the [ValidateModel] attribute to other methods, such as update and delete operations.
[HttpPost]
[ValidateModel]
public IActionResult CreateRegion([FromBody] AddRegionRequestDTO request)
{
// Logic for creating region
return Ok();
}
[HttpPut]
[ValidateModel]
public IActionResult UpdateRegion([FromBody] UpdateRegionRequestDTO request)
{
// Logic for updating region
return Ok();
}
- Run the application.
- Use an API testing tool like Postman or Swagger to send requests.
- Test invalid inputs to ensure the custom action filter catches validation errors.
- Endpoint:
/api/regions - Method: POST
- Body:
{
"code": "A",
"name": "Region Name"
}
{
"errors": {
"Code": [
"Code must be at least 3 characters."
]
}
}
- Cleaner Code: Removes repetitive validation checks from controller methods.
- Centralized Logic: Simplifies maintenance and updates to validation logic.
- Reusable: Easily apply the filter across multiple endpoints.
Using custom action filters in ASP.NET Core enhances code cleanliness and maintainability by handling common logic, like model validation, in a single location. This approach makes controllers more concise and readable while ensuring consistent validation across your API.