0
确保模型的属性只能由ASP.NET WEB.API服务设置的最佳方式是什么?对于该服务的消费者,该属性是只读的。将ASP.NET WEB.API模型属性设置为API的使用者的只读属性?
例如:
public class MyModel
{
[Required]
public string CanBeSetByConsumer { get; set; }
// Can only be set by the service
public int Id { get; set; }
}
public class MyModelController : ApiController
{
public MyModel Get(int id)
{
// get MyModel by Id
return new MyModel();
}
public MyModel Post(MyModel myData)
{
// save myData to a store and generate an ID
// return myData with ID populated with a 201 Created
}
}
在上面的例子中,API的消费者可以POST
:
{
"CanBeSetByConsumer" : "SomeValue"
}
消费者还可以GET
:
{
"Id" : 1234,
"CanBeSetByConsumer" : "SomeValue"
}
我会喜欢做的是如果返回400 BAD REQUEST
客户端POST
s:
{
"Id" : 1234,
"CanBeSetByConsumer" : "SomeValue"
}
一种方法是从Post模型中排除Id属性。 – danludwig 2015-02-24 18:32:42