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