【问题标题】:Remove json field in ASP MVC WebApi Action Method删除 ASP MVC WebApi 操作方法中的 json 字段
【发布时间】:2018-01-15 14:54:23
【问题描述】:

我有一个控制器,它接受这样的模型 UpdateProductCommand:

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

出于安全问题,AuditUserName 字段永远不应设置在外部(来自 API 调用)。

如何从 JSON 请求中删除(或截断)该字段的值?

【问题讨论】:

    标签: asp.net json asp.net-mvc asp.net-web-api model-binding


    【解决方案1】:

    可以通过以下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 会暴露在互联网上。所以有人可能想玩并用原始查询打破它。
    • 这就是为什么我们使用仅包含我们希望从请求中绑定的属性的视图模型:)
    • @StephenMuecke,是的,这是我的第一个方法,但由于其他一些设计要求(长篇大论,大系统)而被我们的技术主管拒绝。
    • 对于Newtonsoft.Json,我们可以在模型/对象上使用一些属性吗? (删除一些属性/字段)
    【解决方案2】:

    这就是 DTO 的用途。

    您可以只创建另一个类(例如UpdateProductCommandDto),它只具有您需要/想要用作输入的属性,然后您可以使用类似Automapper 的东西将其映射到新实例UpdateProductCommand.

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多