Data Validation with Annotations, Custom Attributes, and Fluent Validation

Step 1. Create an ASP.NET Core Web API Project

  1. Open Visual Studio.
  2. Create a new ASP.NET Core Web Application project.
  3. Choose the API template and ensure ASP.NET Core 3.1 or later is selected.
  4. Step 2: Define Dependencies

Data annotations are attributes applied directly to model properties to specify validation rules. Here's how you can implement data validation using data annotations in an ASP.NET Core Web API project.

Step 2. Create the Model

Start by creating a CSharpCornerArticle model with properties that need validation.

using System.ComponentModel.DataAnnotations;

Author: Sardar Mudassar Ali Khan
public class CSharpCornerArticle
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Title is required")]
    public string Title { get; set; }

    [StringLength(500, ErrorMessage = "Content length can't exceed 500 characters")]
    public string Content { get; set; }

    [Range(1, 5, ErrorMessage = "Rating must be between 1 and 5")]
    public int Rating { get; set; }
}

Step 3. Define the Controller

Create a controller that will handle incoming requests and model validation.

using Microsoft.AspNetCore.Mvc;

Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class ArticleController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateArticle([FromBody] CSharpCornerArticle article)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        return Ok("Article created successfully");
    }
}

Step 4. Startup Configuration

In your Startup.cs file, make sure you've configured MVC and added JSON options to respect validation errors.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Author: Sardar Mudassar Ali Khan
public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.WriteIndented = true;
            });
    }

}

In this example, the Required, StringLength, and Range attributes are used for validation. If the validation fails, the API will return a BadRequest response along with detailed error messages.

Remember, you can also implement custom validation attributes if your validation requirements are more complex than what data annotations offer. Additionally, you could use the Fluent Validation library as an alternative to data annotations for more advanced validation scenarios.

Please make sure to install the necessary NuGet packages (Microsoft.AspNetCore.Mvc and Microsoft.AspNetCore.Mvc.NewtonsoftJson) and set up your ASP.NET Core Web API project accordingly before running the code.

Conclusion

Data validation is a crucial aspect of building robust and secure applications. In an ASP.NET Core Web API project, you can implement data validation using data annotations, custom validation attributes, or third-party libraries like Fluent Validation. By applying validation rules directly to your model properties, you ensure that the data entering your application meets the required criteria, reducing the risk of errors, inconsistencies, and security vulnerabilities.

In this example, we focused on using data annotations for validation. We created a CSharpCornerArticle model with various validation attributes such as Required, StringLength, and Range. These attributes specify rules for properties like title, content length, and rating. Within the controller, we checked the model's validity using ModelState.IsValid. If the model was invalid, we returned a BadRequest response with detailed error messages. This process helps to ensure that only valid data is processed by your application's logic.

Remember that as your application grows, your validation requirements might become more complex. For such cases, you can create custom validation attributes to encapsulate specific validation logic and make your code more maintainable. Alternatively, libraries like Fluent Validation provide a powerful way to define complex validation rules in a separate layer, keeping your models clean and your validation logic organized.

By following these practices, you can build reliable ASP.NET Core Web APIs that handle data validation effectively, leading to better data quality, improved user experiences, and enhanced security.


Similar Articles