c# - 验证错误的正确返回类型

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

我需要在我的 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/

相关文章:

c# - 在网页中显示的语法

c# - 该成员没有支持的 SQL 转换。尝试在 LINQ to SQL 语句中访问我的 Partial 类中的属性时。 lambda 表达式?

c# - 从 ActionFilterAttribute 返回带有模型的 View

c# - MVC 3 : How to render a view without its layout page when loaded via ajax?

c# - 为什么我的 Windows 窗体应用程序在不同计算机之间改变大小?

c# - Autofixture,创建一个字典列表<string, object> 交替键

c# - 添加迁移失败,因为未安装 EntityFrameworkCore.Tools

C#对许多相对较大的对象进行垃圾回收

.net - 如何在文档中引用 .Net Framework 类库

asp.net-mvc - 如何重新安装已经在解决方案包目录中的 nuget 包?