How to add a unified model validation processing mechanism to ASP.NET Core

Time:2020-1-7

I. Preface

Model validation is provided by asp.net MVC. We can add data annotations to the properties of model (dto). Before entering action, we will verify whether the input data is legal according to the data annotations. The following describes how to uniformly handle validation and return error information. I don’t have much to say. Let’s have a look at the detailed introduction.

2、 Unified verification of action filter

When we judge the verification status, we usually judge it in actionModelState.IsValidWhether it is true.


public IActionResult Create([FromBody]CreateOrderDto dto)
{
 if(ModelState.IsValid)
 {
  //TODO:...
 }
}

If we write this judgment in every action that needs to be verified, isn’t it too troublesome? Can we verify it before entering all actions? If there is an error, we will directly return the error information instead of executing the action, of course. We can use MVC’s actionfilter, or action filter, to make a unified judgment and processing before executing an action.

1. First, define a general return result class:


public class XcHttpResult
{
 public string Msg { get; set; }
 public bool Result { get; set; }
}

2. Define an actionfilter


public class XcActionFilter : IActionFilter
{
 public void OnActionExecuting(ActionExecutingContext context)
 {
 if (!context.ModelState.IsValid)
 {
  XcHttpResult result = new XcHttpResult() { Result = false };
  foreach (var item in context.ModelState.Values)
  {
  foreach (var error in item.Errors)
  {
   result.Msg += error.ErrorMessage + "|";
  }
  }
  context.Result = new JsonResult(result);
 }
 }
 public void OnActionExecuted(ActionExecutedContext context)
 {
 }
}

3. Configure filter

Configure the filter in startup.cs to take effect:


public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc(options =>
 {
 options.Filters.Add<XcActionFilter>();
 });
}

Three. Test

Define a dto:

public class CreateOrderDto
{
 [required (ErrorMessage = "commodity ID cannot be empty")]
 public string ProductId { get; set; }
 [required (ErrorMessage = "quantity of purchased goods cannot be empty")]
 [range (1, 999, ErrorMessage = "purchase quantity must be between 1 and 999")]
 public int Number { get; set; } = 0;
 [required (ErrorMessage = "user ID cannot be empty")]
 public string UserId { get; set; }
}

Use postman to test the interface:

You can see that it has been verified successfully! Set the value range of commodity quantity to 1 ~ 999, and I entered 9999, which was successfully intercepted and returned error information

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.

Recommended Today

Query SAP multiple database table sizes

Query SAP multiple database table sizes https://www.cnblogs.com/ken-yu/p/12973009.html Item code db02 Here are two approaches, In the first graphical interface, the results of the query data table are displayed in MB, and only one table can be queried at a time. SPACE—Segments—Detailed Analysis—Detailed Analysis  In the pop-up window segment / object, enter the name of the […]