How to suppress - SuppressModelStateInvalidFilter at action level, asp.net core webspi

d khetwal 1 Reputation point
2021-03-03T21:50:20.26+00:00

This is regarding asp.net core web api. How to suppress model state validation at action level. we have [apicontroller] attribute defined at controller level, we want to keep auto model state validation for all the actions except one action method. How we can ignore auto model state validation for a specific action method?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,133 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Wang-MSFT 1,051 Reputation points
    2021-03-04T08:40:17.287+00:00

    Hi, @d khetwal ,

    You could implement FilterAttribute to remove ModelStateInvalidFilter.

    [ApiController]  
    public class PersonController  
    {  
        [SuppressModelStateInvalidFilter]  
        public ActionResult<Person> Get() => new Person();  
    }  
      
    public class SuppressModelStateInvalidFilterAttribute : Attribute, IActionModelConvention  
    {  
        public void Apply(ActionModel action)  
        {  
            for (var i = 0; i < action.Filters.Count; i++)  
            {  
                if (action.Filters[i] is ModelStateInvalidFilter)  
                {  
                    action.Filters.RemoveAt(i);  
                    break;  
                }  
            }  
        }  
    }  
    

    ------
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Michael Wang

    1 person found this answer helpful.