How can i return Json Result + Web api + validate

2019-09-07 17:50发布

问题:

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;
        }
    }
}

Here i want to return message variable with Jsonresult, please help me on it.

回答1:

Try this

    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);
        }
    }

From the client ajax request, on error, get the responseText to process the validation error messages.

You might want to pick a HttpStatusCode based on what you are trying to do, since the