0

I am using ASP.NET Core 5.0 and I have Users Controller with Register method, which receives UserRegisterInputModel. The problem is that all responses from my API are in specific format, but the ApiController auto-validates the input model and returns BadResponse in another format.

This is my abstract response model

    public abstract class ResponseModel
    {
        public ResponseModel(bool successfull, int statusCode)
        {
            this.Successfull = successfull;
            this.StatusCode = statusCode;
            this.ErrorMessages = new List<string>();
        }

        public bool Successfull { get; set; }

        public int StatusCode { get; set; }

        public List<string> ErrorMessages { get; set; }

        public object Data { get; set; }
    }

And this is my BadResponseModel

    public class BadResponseModel : ResponseModel
    {
        public BadResponseModel()
            : base(false, 400)
        {
        }
    }

This is part of my Register method in Users Controller.

        [HttpPost]
        public async Task<IActionResult> Register(UserRegisterInputModel input)
        {
            if (!ModelState.IsValid)
            {
                return Json(new BadResponseModel()
                {
                    ErrorMessages = new List<string>()
                    {
                        "Invalid register information"
                    }
                });
            }

ApiController functionality auto-validates my model and the return statement for BadResponseModel is never reached. Is there any way of stopping auto-validation or changing the default response from ApiController validation ?

  • I think this post already answered your question. [check this out](https://stackoverflow.com/questions/52180323/overriding-badrequest-response-in-asp-net-core-resourcefilter) – Matt Qafouri Apr 28 '21 at 05:41
  • You can use `InvalidModelStateResponseFactory` to generate customized responses. check the following link: [I need to return customized validation result (response) in validation attributes in ASP.Net core Web API](https://stackoverflow.com/questions/64274904/i-need-to-return-customized-validation-result-response-in-validation-attribute/64280264#64280264) and [Handling validation responses for ASP.NET Core Web API](https://www.jerriepelser.com/blog/validation-response-aspnet-core-webapi/). – Zhi Lv Apr 28 '21 at 06:39

1 Answers1

0

You can disable automatic model state validation by using "ApiBehaviourOptions.SuppressModelStateInvalidFilter" property:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.apibehavioroptions.suppressmodelstateinvalidfilter?view=aspnetcore-5.0

So a very basic example of usage would be like that (ConfigureServices method in Startup.cs):

        services.Configure<ApiBehaviorOptions>(opt => { opt.SuppressModelStateInvalidFilter = true; });
ruzgarustu
  • 165
  • 1
  • 7