我正在编写 API。我想允许 PUT 方法更新资源。下面是表示资源的示例模型对象-
var resourceToUpdate = new TestResourceModel()
{
Id = 5
Name = "testName",
Description = "description",
etc...
}
我希望客户端能够 PUT 到/TestResource/5 以更新资源上的属性
现在,假设客户端只想更新属性名称,而不是描述,因此发送以下请求:
Name="testNewName"
在这种情况下,应该更新资源,所以 Name 现在是“testNewName”,Description 仍然是“description”
我如何区分这种情况(在我的 Controller 方法中)与客户端想要将 Description 属性设置为 null 的情况:
Name="testNewName"
Description=
因为我的 Controller 方法看起来像:
[HttpPut]
public ActionResult Index(TestResourceModel model)
{
//True in both cases
bool descriptionSet = model.Description == null;
最佳答案
好吧,您必须将传入值与要更新的值进行比较。我的意思是 null is null is null :) 替代品。在您的模型中设置更新标志 (bool isUpdate),然后仅更改不为空的值。
关于c# - 区分 ASP.NET MVC4 中的空参数和缺失参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241375/