Web Web API中的严格映射(Over-Posting)

我刚刚意识到从查询发送的JSON与我的API之间的映射并不严格。

我给你更多解释:

这是我的C#POCO

public partial class AddressDto { public string AddrId { get; set; } public string Addr1 { get; set; } public string Addr2 { get; set; } public string PostalCode { get; set; } public string City { get; set; } public string Country { get; set; } } 

和REST JSON查询

 PUT http://Localhost:55328/api/ClientAddr/ADD-2059-S002 HTTP/1.1 content-type: application/json { "AddrID": "ADD-2059-S002", "addr1": "B-1/327", "addr2": "1ST FLOOR", "city": "Paris", "Zip_Code": "78956", "country": "France", } 

Web客户端使用Zip_Code发送PUT代替PostalCode。 PostalCode不是疯狂/必需的。 但是我的DTO中不存在Zip_Code。

所以在我的C#代码测试中,模型状态无济于事。

 public HttpResponseMessage Put(string id, AddressDto address) { if (!ModelState.IsValid) return BadRequest(ModelState); // This wont help } 

当客户端使用我的DTO(模型)中不存在的JSON中的内容时,如何引发exception?

如果您需要识别额外的列并将其作为error handling,则必须扩展IModelBinder接口并告诉json反序列化程序将额外的列视为错误并将该错误添加到ModelState。 通过这种方式,您可以在控制器中检查ModelState.IsValid。 查看以下代码

CustomModelBinder

 public class CustomModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.MissingMemberHandling = MissingMemberHandling.Error; ObjToPass obj = new ObjToPass(); ; try { ObjToPass s = JsonConvert.DeserializeObject(actionContext.Request.Content.ReadAsStringAsync().Result, settings); bindingContext.Model = obj; } catch (Exception ex) { bindingContext.ModelState.AddModelError("extraColumn", ex.Message); } return true; } } public class CustomerOrderModelBinderProvider : ModelBinderProvider { public override IModelBinder GetBinder(System.Web.Http.HttpConfiguration configuration, Type modelType) { return new CustomModelBinder(); } } 

传递给webapi的对象类

  public class ObjToPass { public int Id { get; set; } public string Name { get; set; } } 

调节器

  [HttpPost] public void PostValues([ModelBinder(typeof(CustomerOrderModelBinderProvider))] ObjToPass obj) { if(!ModelState.IsValid) { } else { } } 

此示例也适用于HttpPut。

“Over-Posting”:客户端也可以发送超出预期的数据。 例如:

这里,JSON包含Address模型中不存在的属性(“Zip_Code”)。 在这种情况下,JSON格式化程序只是忽略此值。 (XML格式化程序也是如此。)

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api