2015-02-24 69 views
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" 
} 
+0

一種方法是從Post模型中排除Id屬性。 – danludwig 2015-02-24 18:32:42

回答

2

這是一種方法。請注意,POST模型不包含Id屬性。

public class MyGetModel 
{ 
    [Required] 
    public string CanBeSetByConsumer { get; set; } 
    public int Id { get; set; } 
} 

public class MyPostModel 
{ 
    [Required] 
    public string CanBeSetByConsumer { get; set; } 
} 

public class MyModelController : ApiController 
{ 
    public MyGetModel Get(int id) 
    { 
     // get MyModel by Id 
     return new MyGetModel(); 
    } 

    public MyGetModel Post(MyPostModel myData) 
    { 
     // save myData to a store and generate an ID 
     // return myGetData with ID populated with a 201 Created 
    } 
} 

然後,如果你有很多共同的屬性,你可以擁有這兩個從abstract class MyModel繼承。

另一種方法可以將操作篩選器添加到發佈操作中。在該操作篩選器類中,您將覆蓋OnActionExecuting方法,檢查POST值集合中Id鍵下的值,並在那裏設置您的400 BAD REQUEST響應。

public class PreventIdValueAttribute 
    : System.Web.Http.Filters.ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // check request for id value, and if present, 
     // set the result to a 400 bad request HttpResponseMessage 
    } 
} 

[PreventIdValue] 
public MyModel Post(MyModel myData) 
{ 
    // save myData to a store and generate an ID 
    // return myData with ID populated with a 201 Created 
} 

注意,對於第二個選項,您MyModel實例仍會有在Post行動的Id價值,但它的價值將爲零。