我需要在我的 Web API Controller 中实现验证。 在我的类里面,我有一个这样的方法:
public MyEntity Post(MyEntity entity)
{
// ...
}
在 POST 和 PUT 方法中,我通常返回创建/更新的对象。
在 this tutoral他们返回一个HttpResponseMessage
,以便他们可以执行如下操作:
if (ModelState.IsValid)
{
// Do something with the product (not shown).
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
有没有办法使用类似的方法返回保存的实体?
最佳答案
您应该使用HttpRequestMessageExtensions.CreateResponse方法。例如:
if (ModelState.IsValid)
{
// Do something with the product (not shown).
return Request.CreateResponse<MyEntity>(HttpStatusCode.OK, entity);
}
关于c# - 验证错误的正确返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31132378/