Framework era
In the Framework era, when we usually perform parameter verification, the following code is very common
[HttpPost] public async Task<JsonResult> SaveNewCustomerAsnyc(AddCustomerInput input) { if (!) { return Json(()); } ..... }
Or a higher level is to implement IActionFilter for interception, as follows:
public class ApiValidationFilter : IActionFilter { public bool AllowMultiple => false; public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { var method = (); if (method == null) { return await continuation(); } if (!) { var error = (); var result = ($"Parameter verification fails:{error}", ); return (result); } return await continuation(); } }
public static class ModelStateExtensions { /// <summary> /// Get the verification message prompt and format the prompt /// </summary> public static string GetValidationSummary(this ModelStateDictionary modelState, string separator = "\r\n") { if () return null; var error = new StringBuilder(); foreach (var item in modelState) { var state = ; var message = (p => !())?.ErrorMessage; if ((message)) { message = (o => != null)?.; } if ((message)) continue; if ( > 0) { (separator); } (message); } return (); } }
Then register this intercept in the startup item and use it.
.Net Core era
Automatic model status verification
In the era of .Net Core, the framework will help you automatically verify the model's state, which is ModelState. The framework will automatically register the ModelStateInvalidFilter for you, which will run in the OnActionExecuting event.
If we write code based on existing frameworks, we no longer need to couple such model judgment code in the business. The system will check whether ModelState is Valid. If it is InValid, it will directly return 400 BadRequest, so there is no need to execute the subsequent code to improve efficiency. Therefore, the following code is no longer needed in the operation method:
if (!) { return BadRequest(ModelState); }
Problem introduction
In our real development, when we encounter a 400 error that fails to pass a 400 error, we want to return an understandable Json result in the background, rather than returning a 400 error directly on the page. So we need to replace the default BadRequest response result and replace the result with the Json result we want.
Customize BadRequest response
How do we change the default behavior of Core WEB API model validation? The specific method is to configure ApiBehaviorOptions through Startup's ConfigureServices method to implement it. Let's take a look at this class first.
public class ApiBehaviorOptions { public Func<ActionContext, IActionResult> InvalidModelStateResponseFactory { get; set; } public bool SuppressModelStateInvalidFilter { get; set; } public bool SuppressInferBindingSourcesForParameters { get; set; } public bool SuppressConsumesConstraintForFormFileParameters { get; set; } }
All bool types attributes are false by default.
Plan 1
When the SuppressModelStateInvalidFilter property is set to true, the default behavior is disabled
public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddXmlSerializerFormatters() //Set to support XML format input and output .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //Disable default behavior <ApiBehaviorOptions>(options => { = true; }); }
After we disable it, we need to customize the return result. We use the ApiValidationFilter defined above to intercept and return. You need to register this interceptor in the ConfigureServices method
public void ConfigureServices(IServiceCollection services) { ..... services .AddMvc(options => { <ApiValidationFilter>(); }) .AddXmlSerializerFormatters() //Set to support XML format input and output .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
Plan 2
This is also recommended by the official website. If you want to customize the response caused by verification errors, please use InvalidModelStateResponseFactory. This InvalidModelStateResponseFactory is a delegate with an argument with an ActionContext and a return value of IActionResult. The specific implementation is as follows:
public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddXmlSerializerFormatters() //Set to support XML format input and output .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //Parameter verification <ApiBehaviorOptions>(options => { = (context) => { var error = (); return new JsonResult(($"Parameter verification fails:{()}", )); }; }); }
The above code overrides the default behavior (ApiBehaviorOptions) managed by ModelState. When the data model verification fails, the program will execute this code. For a ModelState that fails to pass the verification, return the error message it throws to the client through formatting using JsonResult.
Summarize
In our actual application process, the development of WebApi basically returns custom results for all requests, so we need to override the default override the default model authentication behavior. The above two solutions are given:
The first solution: conforms to the style of the Framework era, and requires additional specifications to override the original model verification (SuppressModelStateInvalidFilter = true)
The second solution: The official recommended approach is in line with the style of the Core era. Just copy the InvalidModelStateResponseFactory commission. I also recommend the second solution.
OK, the above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.