locked
Intercepting validation exception in asp.net core web api RRS feed

  • Question

  • User1838940990 posted

    Hi All,

    In our asp.net core web api 3.1 , we are having validation for models.

    If we give SumInsured  the  maximum range 200000, if we pass 300000 , it give the below response 

    {
      "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
      "title": "One or more validation errors occurred.",
      "status": 400,
      "traceId": "|90e52394-484e4c602b1e5fec.",
      "errors": {
        "SumInsured": [
          "should be greater than 100000 and less than 200000"
        ]
      }
    }


    But I am not able to catch this in  action fitler or exception filter before sending the response.

    below is the implementation of Action filter in my code.

    Can you please let me know your thoughts on this , please correct me if I am wrong any where

    --Model 
    
    public class UserInfo
        {
           [Required]
           [Range(100000,200000,ErrorMessage ="should be greater than {1} and less than {2}")]
            public decimal SumInsured { get; set; }
    
    	 [Required]
            public string Name { get; set; }
    
           [Required]
            [Range(0,80,ErrorMessage ="Age should be a number  than {1} and {2}")]
            public int Age { get; set; }
    
           [Required]
            public DateTime? DateOfBirth { get; set; }
    
        }
    
    
    ---ActionFilter
    
    public class ValidationFilterAttribute : IActionFilter
        {
            public void OnActionExecuted(ActionExecutedContext context)
            {
                if (!context.ModelState.IsValid)
                {
                    context.Result = new BadRequestObjectResult(context.ModelState);
                }
            }
    
            public void OnActionExecuting(ActionExecutingContext context)
            {
                if (!context.ModelState.IsValid)
                {
                    context.Result = new BadRequestObjectResult(context.ModelState);
                }
            }
    
           
        }
    
    
    
    
    
    ---inject dependencies in startup
    
        services.AddControllers(options => {
                    options.Filters.Add(new ApiExceptionFilter());
                    options.Filters.Add(new ValidationFilterAttribute());
                });

    Friday, May 7, 2021 5:07 AM

All replies

  • User1686398519 posted

    Hi techasuran, 

    I want to confirm with you:

    1. Did you use the [ApiController] attribute?
    2. The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response.
    3. To disable the automatic 400 behavior, set the SuppressModelStateInvalidFilter property to true.
      • services.AddControllers()
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters = true;
                options.SuppressModelStateInvalidFilter = true;
                options.SuppressMapClientErrors = true;
                options.ClientErrorMapping[StatusCodes.Status404NotFound].Link =
                    "https://httpstatuses.com/404";
            });

    Best Regards,

    YihuiSun

    Friday, May 7, 2021 6:07 AM
  • User753101303 posted

    Hi,

    And see  https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.apibehavioroptions?view=aspnetcore-5.0 for further configurartion options. Depending on what exactly you want to do you might be able to configure this filter rather than to add your own.

    Friday, May 7, 2021 7:14 AM