2017-08-08 13 views

答えて

0

これは、次のModelBinderによって達成することができます。

public IHttpActionResult UpdateProduct(([ModelBinder(typeof(FieldRemoverModelBinder), Name = nameof(UpdateProductCommand.AuditUserName))]UpdateProductCommand command) 
{ 
    // here command.AuditUserName will always be empty, no matter what's in json 
+1

これはリクエストから削除していない(バインドしていない)。とにかく、このメソッドのコードがそれを設定しているので、そのポイントは何ですか? –

+0

@StephenMuecke - jsonではこのフィールドをすべて送信しませんが、APIはインターネットに公開されます。だから誰かが生のクエリでそれをやりたいのではないかと思うかもしれません。 –

+0

私たちが要求からバインドしたいプロパティだけを含むビューモデルを使用しているのはなぜですか? –

0

のDTOをするためのものである何が:

using Newtonsoft.Json.Linq; 

public class FieldRemoverModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     string content = actionContext.Request.Content.ReadAsStringAsync().Result; 
     JObject json = JObject.Parse(content); 
     JToken property = json.GetValue(bindingContext.ModelName, StringComparison.OrdinalIgnoreCase); 
     property?.Parent.Remove(); 
     bindingContext.Model = json.ToObject(bindingContext.ModelType); 

     return true; 
    } 
} 

はこのようにそれを使用してください。

あなたはちょうどあなたが入力として使用したい/必要なプロパティのみを持つ別のクラス(例えばUpdateProductCommandDto)を作成することができますし、あなただけのUpdateProductCommandの新しいインスタンスにマッピングするAutomapperのようなものを使用することができます。

関連する問題