Disable auto model validation in ASP.NET Core 7 Web API?

540 views Asked by At

I have a ASP.NET Core 7 Web API project with one action method. This action method accepts a model from request body like this:

public class ActionModel
{
    [Required]
    [MaxLength(3)]
    [RegularExpression("[a-zA-Z]+[a-zA-Z]*")]
    public string Name { get; set; }
    public Guid ProfileId { get; set; }
}

Assume that this is my action method:

[HttpPost("extra-data")]
public async Task<ActionResult> MyAction([FromBody] ActionModel requestDto)
{
    if (ModelState.IsValid)
    {
        _logger.LogError("Try to do some thing");
    }

    _logger.LogError($"{ModelState.ErrorCount}");
    return Ok();
}

I expect that the execution goes through the action method body, but the request is validated by some other middleware before reaching the action method. How can I disable this default auto-validation middleware?

1

There are 1 answers

0
arisfan_77 On

In your Startup.cs, maybe try to configure the ApiBehaviour:

public void ConfigureServices(IServiceCollection services)
{
     services.Configure<ApiBehaviorOptions>(options =>
     {
         options.SuppressModelStateInvalidFilter = true;
     });
}