Asp.net web api 是否为API使用者将ASP.NET WEB.API模型属性设置为只读?

Asp.net web api 是否为API使用者将ASP.NET WEB.API模型属性设置为只读?,asp.net-web-api,Asp.net Web Api,确保模型属性只能由ASP.NET WEB.API服务设置的最佳方法是什么?对于服务的使用者,该属性是只读的 例如: public class MyModel { [Required] public string CanBeSetByConsumer { get; set; } // Can only be set by the service public int Id { get; set; } } public class MyModelControlle

确保模型属性只能由ASP.NET WEB.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"
}
消费者还可以
获得

{
  "Id" : 1234,
  "CanBeSetByConsumer" : "SomeValue"
}
如果客户端
POST
s:

{
  "Id" : 1234,
  "CanBeSetByConsumer" : "SomeValue"
}

这里有一种方法。请注意,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
    }
}
然后,如果您有许多共享属性,那么您可以让这两个属性都继承自
抽象类MyModel

另一种方法是在操作后添加操作过滤器。在该操作筛选器类中,您将重写
OnActionExecuting
方法,检查POST values集合中
Id
键下的值,并在那里设置400错误请求响应

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
值,但其值将为零

一种方法是从Post模型中排除
Id
属性。