【问题标题】:Correct return type for validation errors验证错误的正确返回类型
【发布时间】:2015-06-30 07:41:29
【问题描述】:

我需要在我的 web api 控制器中实现验证。 在我的课堂上,我有一个这样的方法:

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);
}

有没有办法使用类似的方法返回保存的实体?

【问题讨论】:

标签: c# .net asp.net-mvc asp.net-web-api


【解决方案1】:

您应该使用HttpRequestMessageExtensions.CreateResponse 方法。例如:

if (ModelState.IsValid)
{
    // Do something with the product (not shown).

    return Request.CreateResponse<MyEntity>(HttpStatusCode.OK, entity);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 2022-01-08
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2017-12-17
    • 2022-11-09
    • 1970-01-01
    相关资源
    最近更新 更多