检测 frombody post 负载中的额外属性

detect extra attributes in frombody post payload

我正在寻找一种方法来检测在 WebAPI post 负载上传送的额外属性,这些属性与我期望的 POCO 不匹配。例如,这里有一个输入 object:

public class Input
{
    public string Name { get; set; }
}

和控制器方法:

public void Post([FromBody]Input value)

如果客户端发送以下 post 负载:

{
    "Name" : "Foo",
    "Description" : "Bar"
}

这将在我的控制器上触发 Post 方法并填充名称。我想知道 Description 已发送但被忽略,因此我可以记录该事件服务器端或通过响应 header 通知客户端他们正在发送额外数据。

我认为这是可能的,但如果您想要一个通用的解决方案,则必须不使用模型绑定并使用反射:

Class:

public class Input
{
    public string Name { get; set; }
}

有效负载:

{
    "Name" : "Foo",
    "Description" : "Bar"
}

控制器方法:

public async void Post()
{
    //Read the content to a string   
    var content = await Request.Content.ReadAsStringAsync();

    //Get the Input object you wanted
    var input = JsonConvert.DeserializeObject<Input>(content);

    //Get a Dictionary containing all the content sent    
    var allContent = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);

    //Get the property names of the wanted object    
    var props = input.GetType().GetProperties().Select(a => a.Name);

    //See which properties are extra
    var extraContent = allContent.Keys.Except(props);
}

对于上面的示例,extraContent 将是一个包含 "Description" 的列表。如果你想要这个值,只需使用字典对象。