未通过模型验证的字段列表

时间:2017-12-08 23:16:42

标签: asp.net asp.net-mvc asp.net-web-api2

我正在研究ASP.NET WebAPI,它为json服务器阵列服务,并获得一系列mofications。

[ValidateModel]
public IHttpActionResult POSTClient(Client[] clients)
{
    foreach (Client c in clients)
    {
         ClientBLL.ModyfiClient(c);
    }
    return Ok();
}    


public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            var errorsList = new List<string>();
            foreach(var modelError in actionContext.ModelState)
            {
                errorsList.Add(modelError.Key);
            }
            var response = new
            {
                errorThrow = "invalid model",
                errors = errorsList,
                sender = "api",
                status = "customerror"
            };

            actionContext.Response = actionContext.Request.CreateResponse(
                HttpStatusCode.BadRequest, response, actionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
        }
    }
}

我正在

{
    "errorThrow": "invalid model",
    "errors": [
        "clients[0]",
        "clients[1]"
    ],
    "sender": "api",
    "status": "customerror"
}

但我想以特定的方式返回ValidateModel错误,数组条目数和未通过验证的字段名称。如何从actionContext.ModelState获取字段名称?

0 个答案:

没有答案