0
string message = string.Empty;

public override void OnActionExecuting(HttpActionContext actionContext)
{
    var modelState = actionContext.ModelState;

    if (!modelState.IsValid)
        actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);

    foreach (var key in modelState.Keys)
    {
        var state = modelState[key];

        if (state.Errors.Any())
        {
            message = message + state.Errors.First().ErrorMessage;
        }
    }
}

在这里我想用 Jsonresult 返回消息变量,请帮助我。

4

1 回答 1

0

试试这个

    public override void OnActionExecuting(HttpActionContext context)
    {
        var modelState = context.ModelState;
        if (!modelState.IsValid)
        {
            var errors = new JObject();
            foreach (var key in modelState.Keys)
            {
                var state = modelState[key];
                if (state.Errors.Any())
                {
                    errors[key] = state.Errors.First().ErrorMessage;
                }
            }

            context.Response = context.Request.CreateResponse<JObject>(HttpStatusCode.BadRequest, errors);
        }
    }

从客户端 ajax 请求中,如果出错,获取 responseText 以处理验证错误消息。

您可能希望根据您要执行的操作来选择 HttpStatusCode,因为

于 2012-12-12T07:22:35.667 回答