WebApi POST not to include ID field

耗尽温柔 提交于 2019-12-07 11:37:20

问题


I am still just a couple days into ASP.NET and WebAPI frameworks so I must be missing out something really simple.

I have a model that has a couple properties and ID (as a property, which has a private setter but that didn't help).

public long ID { get; private set; }

[Required(ErrorMessage = "Location coordinate X is required.")]
public double X { get; set; }

[Required(ErrorMessage = "Location coordinate Y is required.")]
public double Y { get; set; }

And then I have a controller method post:

public HttpResponseMessage Post(MyModel model)

When I start the project and go to auto-generated API documentation, I can see that samples include ID as an input field. I want API to ignore ID input field. I could just ignore it myself but I don't like such must-remember-not-to-use things in my code.

One option would be to create a separate model just for the input but it would mean I have to maintain two classes instead of one.

Is there any data annotation to ignore this property entirely?


回答1:


Try with:

[ScaffoldColumn(false)]

The ID property will no longer be seen by the html helpers. However, the model binder might still try to move a value into the ID property if it sees a matching value in the request.

So you decorate it with Exclude to avoid property to be binded:

[Exclude]
 public long ID { get; set; }

You can also , (inside your Post function) remove the property from state:

  ModelState.Remove("Id"); // Key removal

    if (ModelState.IsValid)
       {

       }
    }


来源:https://stackoverflow.com/questions/19375199/webapi-post-not-to-include-id-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!