2017-08-08 110 views
1

刪除JSON場我接受這樣的模型UpdateProductCommand控制器:在ASP MVC的WebAPI操作方法

public IHttpActionResult UpdateProduct(UpdateProductCommand command) 
{ 
    command.AuditUserName = this.RequestContext.Principal.Identity.Name; 
    // .... 
} 

對於安全問題,AuditUserName領域不應該被外界設定(由API)。

如何從JSON請求中刪除(或截斷)該字段的值?

回答

0

可以實現由以下ModelBinder

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; 
    } 
} 

使用方法如下:

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將會暴露在Internet中。所以有人可能想玩,並用原始查詢進行分解。 –

+0

這就是爲什麼我們使用視圖模型,只包含那些我們想要從請求中綁定的屬性:) –

0

這就是DTO的是。

你可以只創建另一個類(UpdateProductCommandDto例如)只具有你需要/想用作輸入的屬性,然後你可以使用類似Automapper將其映射到UpdateProductCommand一個新的實例。