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.

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top