简体   繁体   中英

Asp.Net Core 2.1 ApiController attribute doesn't validate Model

I'm using .NET Core 2.1.

This is my controller:

namespace MyApp.Controllers
{
   /// <summary>
   /// Cost controller
   /// </summary>
   [Route("api/v1/[controller]")]
   [Produces("application/json")]
   [ApiController]
   public class CostController : ControllerBase
   {

And one of the routes:

        /// <summary>
        /// Estimate cost
        /// </summary>
        /// <param name="info">Processing information</param>
        [HttpPost("estimate")]
        public IActionResult Estimate(ProcessingInfo info)

ProcessingInfo is defined like this:

public class ProcessingInfo
{
    [Range(0.0000001, double.MaxValue)]
    [JsonProperty(PropertyName = "inputSizeGB", Required = Required.Always)]
    public double InputSizeGB { get; set; }
}

In Startup.cs , I have the following lines:

services.AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

I also tried without the SetCompatibilityVersion .

Be it through integration tests using TestServer, or using Postman, if I send an invalid model:

{
  "inputSizeGB": -1
}

I get a 200-OK response, and not the expected BadRequest 400: 邮差

Note that if I manually add a check with if (!ModelState.IsValid) the model is declared invalid.

All this is from an existing codebase, so I'm frantically searching for what can cause such a side effect but so far I've been unlucky.

So I found the issue, some set up services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true); in the services configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM