POST的WebAPI不包括ID字段 [英] WebApi POST not to include ID field
问题描述
我仍然只是一对夫妇天进ASP.NET和的WebAPI框架,所以我一定是错过了很简单的东西。
I am still just a couple days into ASP.NET and WebAPI frameworks so I must be missing out something really simple.
我有了一对夫妇的性能和标识(如一个属性,它拥有一个私人二传手,但没有帮助)的模型。
I have a model that has a couple properties and ID (as a property, which has a private setter but that didn't help).
public long ID { get; private set; }
[Required(ErrorMessage = "Location coordinate X is required.")]
public double X { get; set; }
[Required(ErrorMessage = "Location coordinate Y is required.")]
public double Y { get; set; }
然后,我有一个控制器方法后:
And then I have a controller method post:
public HttpResponseMessage Post(MyModel model)
当我启动项目并进入自动生成API文档,我可以看到,样品包括ID作为输入字段。 我要API忽略ID输入字段。我可以不理自己,但我不喜欢这样的必须记住,不使用的的东西在我的code。
When I start the project and go to auto-generated API documentation, I can see that samples include ID as an input field. I want API to ignore ID input field. I could just ignore it myself but I don't like such must-remember-not-to-use things in my code.
一种选择是创建一个单独的模型只是为输入,但是这将意味着我必须保持,而不是一个两个班。
One option would be to create a separate model just for the input but it would mean I have to maintain two classes instead of one.
是否有任何数据注解完全忽略这个属性?
Is there any data annotation to ignore this property entirely?
推荐答案
试着用:
[ScaffoldColumn(false)]
ID属性将不再由HTML辅助看到。然而,模型绑定可能仍然试图将一个值移动到ID属性,如果它在请求中看到一个匹配值。
The ID property will no longer be seen by the html helpers. However, the model binder might still try to move a value into the ID property if it sees a matching value in the request.
所以,你装饰它与排除,以避免财产被绑定:
So you decorate it with Exclude to avoid property to be binded:
[Exclude]
public long ID { get; set; }
您也可以从状态删除属性(您的Post函数中):
You can also , (inside your Post function) remove the property from state:
ModelState.Remove("Id"); // Key removal
if (ModelState.IsValid)
{
}
}
这篇关于POST的WebAPI不包括ID字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!