How can i return Json Result + Web api + validate model + actionfilters +OnActionExecuting method

我与影子孤独终老i 提交于 2019-12-12 05:39:23

问题


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



来源:https://stackoverflow.com/questions/13584508/how-can-i-return-json-result-web-api-validate-model-actionfilters-onactio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!