Return JSON with error status code MVC


I was trying to return an error to the call to the controller as advised in This link so that client can take appropriate action. The controller is called by javascript via jquery AJAX. I am getting the Json object back only if I don't set the status to error. Here is the sample code

if (response.errors.Length > 0)
   Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(response);

I get the Json if I don't set the statuscode. If I set the status code I get the status code back but not the Json error object.

Update I want to send an Error object as JSON so that it can be handled error callback of ajax.

This question is tagged with c# json

~ Asked on 2012-07-06 22:03:21

The Best Answer is


I found the solution here

I had to create a action filter to override the default behaviour of MVC

Here is my exception class

class ValidationException : ApplicationException
    public JsonResult exceptionDetails;
    public ValidationException(JsonResult exceptionDetails)
        this.exceptionDetails = exceptionDetails;
    public ValidationException(string message) : base(message) { }
    public ValidationException(string message, Exception inner) : base(message, inner) { }
    protected ValidationException(
    System.Runtime.Serialization.SerializationInfo info,
    System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }

Note that I have constructor which initializes my JSON. Here is the action filter

public class HandleUIExceptionAttribute : FilterAttribute, IExceptionFilter
    public virtual void OnException(ExceptionContext filterContext)
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");
        if (filterContext.Exception != null)
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
            filterContext.Result = ((ValidationException)filterContext.Exception).myJsonError;

Now that I have the action filter, I will decorate my controller with the filter attribute

public JsonResult UpdateName(string objectToUpdate)
   var response = myClient.ValidateObject(objectToUpdate);
   if (response.errors.Length > 0)
     throw new ValidationException(Json(response));

When the error is thrown the action filter which implements IExceptionFilter get called and I get back the Json on the client on error callback.

~ Answered on 2012-07-12 00:36:57


The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

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;

You can then use this in your controller action like so:

    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);

~ Answered on 2017-03-28 12:41:55

Most Viewed Questions: