In the.net Core era, the framework automatically validates the state of your model, that is, model State. The framework will automatically register the ModelStateInvalidFilter for you and this will run in an OnActionExecuting event.
Based on the existing framework code, so we no longer need to coupling such model judgment code in the business, the system will check whether the ModelState is Valid, if it is InValid, it will directly return 400 BadRequest, so there is no need to execute the following code, improve efficiency. Therefore, the following code is no longer needed in the action method:
if(! ModelState.IsValid) {return BadRequest(ModelState);
}
Copy the code
The first method:.NET Core disables model validation filters
services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true);
Copy the code
SuppressModelStateInvalidFilter = true, will shut the default model validation filters. [ApiController] Provides 400 model verification by default and has a high priority. If you want to customize model verification, disable the default model verification. The second method: automatically replace the default model validation
// Validate parameters
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = (context) =>
{
var error = context.ModelState.GetValidationSummary();
return new JsonResult(Result.FromError($" parameter verification failed:{error.ToString()}", ResultCode.InvalidParams));
};
});
Copy the code