Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

asp net core web api custom model validation

Asp net core web API, I am trying to return a custom response for the model validator. But ValidateModelFilter is not called when the required field, not in the request.

ValidateModelFilter.cs

public class ValidateModelFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
             var response = new Model
             {
                 error = context.ModelState.ToString()
             };
             context.Result = new BadRequestObjectResult(response);
         }
    }
}

Startup.cs

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

I am getting a response like this

{
  "errors": {
    "Firstname": [
      "The Firstname field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|e6752549-4142e91f1074e978."
}

I want to return a response like

{
"error": "The Firstname field is required."
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The link shows how we have to disable the default Model Binding Exception filter that is returning a 400 error and short circuits the pipeline. Only then the OnActionExecuting method in our custom ActionFilterAttribute is actually getting executed. Everything then works as expected.

https://stackoverflow.com/a/51522487/14924779


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...