c# - .NET Web API - ModelState 的错误响应

标签 c# asp.net-web-api2

我正在使用 .NET Web API 2.2 在 C# 中构建 API。我正在验证请求并通过 ModelState 返回“错误”响应。

[ResponseType(typeof(IEnumerable<CustomerModel>))]
public IHttpActionResult Get([FromBody]List<CustomerSearchModel> row)
{
    if (ModelState.IsValid)
    {
        CustomerLookupModel model = new CustomerLookupModel(row);
        model.Init();
        model.Load();

        return Ok(model.Customers);
    }
    else
    {
        return BadRequest(ModelState);
    }
}

这是一个示例“错误”响应。

{
    "message": "The request is invalid.",
    "modelState": {
        "row[0].Country": ["'Country' should not be empty."]
    }
}

在“错误”响应中,我想将“modelState”一词更改为“错误”。我想我可以通过复制“ModelState”对象并将其命名为“error”来做到这一点……并将其包含在 BadRequest 中。

return BadRequest(error);

那没用。我一定是遗漏了一些简单的东西。

最佳答案

返回匿名对象:

 public HttpResponseMessage GetModelStateErrors()
    {

        //return Request.CreateResponse(HttpStatusCode.OK, new Product());

        ModelState.AddModelError("EmployeeId", "Employee Id is required.");
        ModelState.AddModelError("EmployeeId", "Employee Id should be integer");
        ModelState.AddModelError("Address", "Address is required");
        ModelState.AddModelError("Email", "Email is required");
        ModelState.AddModelError("Email", "Invalid Email provided.");

        var error = new {
            message = "The request is invalid.",
            error = ModelState.Values.SelectMany(e=> e.Errors.Select(er=>er.ErrorMessage))
        };

        return Request.CreateResponse(HttpStatusCode.BadRequest, error);
    }

fiddler 输出:

enter image description here

关于c# - .NET Web API - ModelState 的错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39177299/

相关文章:

c# - 如何在 Windows Phone 7 中以编程方式检索下载的文件?

odata - 在 Web API 2.2 上将 $select 和 $expand 与 Odata v4.0 一起使用时出错

asp.net - 使用授权代码流的Web API OAuthAuthorizationServer

c# - ASP.NET Web API C# 并发请求导致数据库重复

c# - 使用 Windows 客户端应用程序防止跨站点请求伪造攻击

c# - 使用 Linq 从 Json 中选择包含子对象的对象

c# - 将对象列表写入文本文件

c# - Amazon 和 Evernote 的身份验证设置

c# - 如何在 ASP.NET MVC 中应用评级

asp.net-web-api - ASP.NET Web Api 2.0 中哪个优先,ExceptionFilter 还是 ExceptionHandler?