Disable Model Validation in Asp.Net MVC

前端 未结 7 953
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 20:41

How do I disable Model validation for a single Action in a Controller ? Or can I do it per model by registering the model type at startup somewhere ?

I want the Mode

相关标签:
7条回答
  • 2020-12-09 21:43

    I definitely dislike this addition in the 2.0 version, because, as you stated in your question, validation makes more sense in the Service layer. In this way you can reuse it in other non-web applications, and test it more easily without having to mock the auto-validation mechanism.

    Validation in Controller layer is pointless because in this part you can only verify model data and not business rules. For example, think of a service responsible of adding new comments and a user that wants to post a new one, the data in the comment he/she is posting may be valid, but what happens if the user is banned to comment because of misbehavior in the past? You should do some validation in the Service layer to ensure this is not happening, and if it does, throwing an exception. In short, validation must be done in the Service layer.

    I use xVal as my Validation framework because it's compatible with the DataAnnotationModel, allows me to place validation wherever I want and performs client-side validation without extra-effort, even remote-client side. This is how I use it at the beginning of each of my services, for example, a login service:

    public void SignIn(Login login) {
        var loginErrors = DataAnnotationsValidationRunner.GetErrors(login);
    
        // Model validation: Empty fields?
        if (loginErrors.Any())
            throw new RulesException(loginErrors);
    
        // Business validation: Does the user exist? Is the password correct?
        var user = this._userRepository.GetUserByEmail(login.Email);
    
        if (user == null || user.Password != login.Password)
    
            throw new RulesException(null, "Username or password invalids");
    
        // Other login stuff...
    }
    

    Simple, web-independent and easy... then, in the Controller:

    public RedirectResult Login(Login login) {
    
        // Login the user
    
        try {
    
            this._authenticationRepository.SignIn(login);
    
        } catch (RulesException e) {
    
            e.AddModelStateErrors(base.ModelState, "Login");
    
        }
    
        // Redirect
    
        if (base.ModelState.IsValid)
            return base.Redirect(base.Url.Action("Home"));
        else return base.Redirect(base.Url.Action("Login"));
    }
    
    0 讨论(0)
提交回复
热议问题