asp.net-web-api - 如何避免将空实体对象传递给 web api 方法
问题描述
我有下面的web api方法如下
public bool UpdateValidations([FromBody] ValidationKeyEntity validationKey)
{
if (ModelState.IsValid)
{
//my code here
}
}
public class ValidationKeyEntity
{
public int ValidationKeyId { get; set; }
[MaxLength(Constants.maxStringLength)]
public string Name { get; set; }
public int DisplayId { get; set; }
[MaxLength(Constants.maxStringLength)]
public string CreatedBy { get; set; }
}
我正在使用 Postman 进行测试。我将与 ValidationKeyEntity 对象不同的 json 作为 { "Vishal": "vishal" } 作为参数传递。但我的 ModelState.IsValid 仍然返回 true。
如何避免接受除“ValidationKeyEntity”对象之外的其他 json 对象?
解决方案
使用RequiredAttribute将属性标记为
required
:public class ValidationKeyEntity { [Required] public int ValidationKeyId { get; set; } [Required] public string Name { get; set; } [Required] public int DisplayId { get; set; } [Required] public string CreatedBy { get; set; } }
全局设置MissingMemberHandling以处理废物属性:
var httpConfiguration = new HttpConfiguration(); httpConfiguration .Formatters .JsonFormatter .SerializerSettings .MissingMemberHandling = MissingMemberHandling.Error;
推荐阅读
- pytorch - 不使用多处理但在使用 PyTorch DataLoader 时在 google colab 上出现 CUDA 错误
- python - 无法使用 python 在 tkinter 中将图像显示为背景
- amazon-s3 - S3 Blob 的唯一资源标识符
- vue.js - Vuetify 在数据表中插入操作按钮并获取行数据
- javascript - 在 javascript 中否定正则表达式中的模式时出错
- javascript - 在条件下重新调用 $.ajax
- python - 计算python中选项卡的出现次数
- ios - 为什么可访问性将 NSString 属性添加为静态文本?以及如何忽略它?
- elm - 如何在显示的代码片段中显示语法突出显示?
- reactjs - 使用 React 上下文将输入数据从组件 A 传递到组件 B