2017-12-04 6 views
0

Ich führe einen benutzerdefinierten WebApi2 Modellbinder wie folgt aus: Dies erstellt das Modell erfolgreich. Ich unterdrücke die JSON-Serializer-Fehler, da sie nicht den gleichen Fehlern entsprechen, die normalerweise vom Standardmodellbinder bereitgestellt werden.Validierung eines Modells bei Verwendung eines benutzerdefinierten Modellbinders in webapi2

Egal, ob "erforderlich" und andere Attribute im Modell, ModelState ist leer.

Wie ich entweder

  • Rufen Sie das Standardbinder Modell die PartyModel mit allen relevanten Modellzustandsfehler zu erhalten?
  • Führen Sie den Standard-Model-Validator aus, um den Modellstatus mit den relevanten Fehlern zu füllen, nachdem Sie die Eigenschaften serialisiert haben, die ich bekommen kann?

.

public bool BindModel(
     HttpActionContext actionContext, 
     System.Web.Http.ModelBinding.ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType != typeof(PartyModel)) 
      return false; 

     var json = actionContext.Request.Content.ReadAsStringAsync().Result; 
     var settings = new JsonSerializerSettings 
      { 
       TypeNameHandling = TypeNameHandling.Auto, 
       // ignore json serializer errors, as they don't 
       // seem to mimic the webapi2 default validator names/descriptions. 
       Error = (s, e) => e.ErrorContext.Handled = true 
      }; 
     var model = JsonConvert.DeserializeObject<PartyModel>(json, settings); 

     // at this point the model needs to be validated. 

     bindingContext.Model = model; 
     return true; 
    } 

Antwort

0
public bool BindModel(
     HttpActionContext actionContext, 
     System.Web.Http.ModelBinding.ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType != typeof(PartyModel)) 
      return false; 
     ... 

     // following lines invoke default validation on model 
     bindingContext.ValidationNode.ValidateAllProperties = true; 
     bindingContext.ValidationNode.Validate(actionContext); 
     return true; 
    } 
Verwandte Themen