SoFunction
Updated on 2025-04-05

Method for parameter verification using FluentValidate in .Net Web Api

Preface

This article mainly introduces the relevant content on the verification of .Net Web Api using FluentValidate parameters. I won’t say much below, let’s take a look at the detailed introduction together.

The method is as follows

Install FluentValidate

Please install the version in the Web API

Create a Model that needs to be verified

 public class Product 
 {
  public string name { get; set; }
  public string des { get; set; }
  public string place { get; set; }
 }

Configuring FluentValidation requires inheriting the AbstractValidator class and adding corresponding verification rules.

 public class ProductValidator : AbstractValidator<Product>
 {
  public ProductValidator()
  {
   RuleFor(product => ).NotNull().NotEmpty();//The name field cannot be null, nor can it be an empty string  }
 }

Configuring FluentValidation in Config

Add in WebApiConfig configuration file

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  // Web API routes
  ...
  (config);
 }
}

Verify parameters

Verification is required before entering the Controller. If there is an error, it will be returned. It will no longer enter the Controller. It is necessary to use ActionFilterAttribute.

public class ValidateModelStateFilter : ActionFilterAttribute
{
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
  if (!)
  {
    = (, );
  }
 }
}

If you want this filter to work for all controllers, register in WebApiConfig

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  // Web API configuration and services
  (new ValidateModelStateFilter());

  // Web API routes
  ...

(config);
 }
}

If it works for a controller, you can register it in the controller

[ValidateModelStateFilter]
public class ProductController : ApiController
{
 // Specific logic}

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.