2015-02-24 63 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价值,但它的价值将为零。