可以實現由以下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
這不是從請求中刪除它(它只是沒有綁定它)。既然你的方法中的代碼是無論如何設置它,有什麼意義? –
@StephenMuecke - 我不會在json中將這個字段全部發送出去,但是API將會暴露在Internet中。所以有人可能想玩,並用原始查詢進行分解。 –
這就是爲什麼我們使用視圖模型,只包含那些我們想要從請求中綁定的屬性:) –