区分ASP.NET MVC4中的null和missing参数

我正在写一个API。 我想允许PUT方法更新资源。 下面是一个表示资源的示例模型对象 –

var resourceToUpdate = new TestResourceModel() { Id = 5 Name = "testName", Description = "description", etc... } 

我希望客户端能够PUT到/ TestResource / 5来更新资源的属性

现在,假设客户端只想更新属性Name,而不是更新描述,因此发送以下请求:

 Name="testNewName" 

在这种情况下,应该更新资源,因此Name现在是“testNewName”,put描述仍然是“描述”

我如何区分这种情况(在我的Controller方法中),以及客户端想要将Description属性设置为null的情况:

 Name="testNewName" Description= 

因为我的控制器方法将如下所示:

 [HttpPut] public ActionResult Index(TestResourceModel model) { //True in both cases bool descriptionSet = model.Description == null; 

那么你必须将传入的值与你想要更新的值进行比较。我的意思是null是null是null 🙂 Alt。 在模型中设置更新标志(bool isUpdate),然后只更改非空值。