Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to disable model validation in ASP.Net Core 2 MVC

Set up MVC with the extension method

services.AddMvc()

Then in a controller, and this may apply to GET also, create a method for the POST action with a parameter supplied in the body, e.g.

[HttpPost("save")]
public Entity Save([FromBody]Entity someEntity)

When the action is called the MVC pipeline will call the ParameterBinder which in turn calls DefaultObjectValidator. I don't want the validation (its slow for one thing, but more importantly is looping on complex cyclical graphs), but it seems the only way to turn off validation in the pipeline is something like this:

public class NonValidatingValidator : IObjectModelValidator
{
    public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model)
    {
    }
}

and in the StartUp/ConfigureServices:

        var validator = services.FirstOrDefault(s => s.ServiceType == typeof(IObjectModelValidator));
        if (validator != null)
        {
            services.Remove(validator);
            services.Add(new ServiceDescriptor(typeof(IObjectModelValidator), _ => new NonValidatingValidator(), ServiceLifetime.Singleton));
        }

which seems like a sledgehammer. I've looked around and can't find an alternative, also tried to remove the DataAnnotationModelValidator without success, so would like to know if there's a better/correct way to turn off validation?

like image 557
S Waye Avatar asked Sep 23 '17 01:09

S Waye


People also ask

How do I disable a validator?

Click Window > Preferences and select Validation in the left pane. The Validation page of the Preferences window lists the validators available in your project and their settings. To disable individual validators, clear the check boxes next to each validator that you want to disable.

How do you disable server side validation?

To disable a validation controlSet the validation control's Enabled property to false.

What is enable and disable client side validation in ASP.NET MVC?

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.


1 Answers

 services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });

should disable automatic model state validation.

like image 87
aseaSharp Avatar answered Sep 20 '22 11:09

aseaSharp