.NET Web API - 使用ModelState的错误响应

Bil*_*ill 8 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个示例'错误'响应.

{
    "message": "The request is invalid.",
    "modelState": {
        "row[0].Country": ["'Country' should not be empty."]
    }
}
Run Code Online (Sandbox Code Playgroud)

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

return BadRequest(error);
Run Code Online (Sandbox Code Playgroud)

那没用.我一定很遗憾.

Dev*_*per 18

返回匿名对象:

 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);
    }
Run Code Online (Sandbox Code Playgroud)

提琴手输出:

在此输入图像描述

  • 你好...我不明白你的回答。ModelState 是字典。我最终使用了这种方法 - http://www.khalidabuhakmeh.com/a-better-validation-result-for-asp-net-webapi (2认同)