How to show the JSON Result with 400 error Code.

I tried to find the way to return 400 error code with JSON error result.

I think this is the best way and easy to implement.

Create the custom class as below.

    public class JsonHttpStatusResult : JsonResult
    {
        private readonly HttpStatusCode _httpStatus;

        public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
        {
            Data = data;
            _httpStatus = httpStatus;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
            context.RequestContext.HttpContext.Request.ContentType = "application/json";
            base.ExecuteResult(context);
        }
    }

From the controller, return the result with above custom class.

if (validationInfo.Errors.Any())
{
    return new JsonHttpStatusResult(validationInfo, HttpStatusCode.BadRequest);
}

Leave a Reply