Return JSON with error status code MVC

asp net return json
return json exception mvc
return json to view mvc
asp net mvc return json from file
.net core return json with status code
mvc return json array from controller
asp.net core return json
return json with message

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.


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.Clear();
            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

[HandleUIException]
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.

ASP.NET Core return JSON with status code, The way to get control over the status results, is you need to return a ActionResult The chunk of code above is mostly a duplicate of the AddMvc() method. //​GET http://example.com/api/test/asjson [HttpGet("AsJson")] public JsonResult  http status code Sometimes I need just return http status code as response to XHR call in asp.net mvc and it's really annoying, at least for me, fast googling how to do it. So, let me share my first and fast tip how to return http response codes.


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;
        base.ExecuteResult(context);
    }
}

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

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

Returning a JsonResult within the Error function of JQuery Ajax , MVC » Returning a JsonResult within the Error function of JQuery Ajax by changing the Response Header with a Http Code that is different  As of the date of 2017-07-08, Patrick Desjardins has been employee by Netflix. Before, from 2014-08-01 to 2017-07-08, employee by Microsoft Corporation.


There is a very elegant solution to this problem, just configure your site via web.config:

<system.webServer>
    <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough"/>
</system.webServer>

Source: https://serverfault.com/questions/123729/iis-is-overriding-my-response-content-if-i-manually-set-the-response-statuscode

how i can show the error 500 status code in ASP.NET MVC for json , I want to return error 500 status code as json when ASP.NET return text/html by default. when a parameter missing the error should be return in  Several of the responses rely on an exception being thrown and having it handled in the OnException override. In my case, I wanted to return statuses such as bad request if the user, say, had passed in a bad ID.


Building on the answer from Richard Garside, here's the ASP.Net Core version

public class JsonErrorResult : JsonResult
{
    private readonly HttpStatusCode _statusCode;

    public JsonErrorResult(object json) : this(json, HttpStatusCode.InternalServerError)
    {
    }

    public JsonErrorResult(object json, HttpStatusCode statusCode) : base(json)
    {
        _statusCode = statusCode;
    }

    public override void ExecuteResult(ActionContext context)
    {
        context.HttpContext.Response.StatusCode = (int)_statusCode;
        base.ExecuteResult(context);
    }

    public override Task ExecuteResultAsync(ActionContext context)
    {
        context.HttpContext.Response.StatusCode = (int)_statusCode;
        return base.ExecuteResultAsync(context);
    }
}

Then in your controller, return as follows:

// Set a json object to return. The status code defaults to 500
return new JsonErrorResult(new { message = "Sorry, an internal error occurred."});

// Or you can override the status code
return new JsonErrorResult(new { foo = "bar"}, HttpStatusCode.NotFound);

Return JSON with error status code MVC, 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. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.


You have to return JSON error object yourself after setting the StatusCode, like so ...

if (BadRequest)
{
    Dictionary<string, object> error = new Dictionary<string, object>();
    error.Add("ErrorCode", -1);
    error.Add("ErrorMessage", "Something really bad happened");
    return Json(error);
}

Another way is to have a JsonErrorModel and populate it

public class JsonErrorModel
{
    public int ErrorCode { get; set;}

    public string ErrorMessage { get; set; }
}

public ActionResult SomeMethod()
{

    if (BadRequest)
    {
        var error = new JsonErrorModel
        {
            ErrorCode = -1,
            ErrorMessage = "Something really bad happened"
        };

        return Json(error);
    }

   //Return valid response
}

Take a look at the answer here as well

JsonResult Type in MVC, JsonResult is an ActionResult type in MVC. It helps Step 4: To fix the preceding error add the following code in the JsonDemoController file. It returns with 200 OK status code (it's an Ok type of ObjectResult) It does content negotiation, i.e. it'll return based on Accept header in request. If Accept: application/xml is sent in request, it'll return as XML. If nothing is sent, JSON is default. If it needs to send with specific status code, use ObjectResult or StatusCode instead. Both does the same thing, and supports content negotiation.


ASP.Net MVC: Using Json Standard Responses for your Ajax Calls , Net MVC: Using Json Standard Responses for your Ajax Calls. For the past This is what we have been using to generate the Standard Response (yes, is VERY simple) . return new { Success = false , ErrorMessage = error }; This code simulates a click event that posts into our controller using jQuery. return Json(db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault(), JsonRequestBehavior.AllowGet); Now, let’s code our jQuery events to make a Ajax call to detailsasjson() action method to get the json result and populate the details div using $.Ajax() method in jQuery.


Format response data in ASP.NET Core Web API, NET Core MVC has support for formatting response data. For example, returning JsonResult returns JSON-formatted data. For example, returning different HTTP status codes based on the result of operations performed. Exception handling is one of the primary concerns in any applications we develop. It is also very important that we should not emit any technical details when the application breaks.


ASP.NET Core MVC Global Error Handling for HTML and AJAX , NET Core MVC Global Error Handling for HTML and AJAX Endpoints The way we can detect if an AJAX request expects a JSON response is by StatusCode = statusCode; var problemDetails = new ProblemDetails { Title  ASP.NET Core - Return 500 (Internal Server Error) or any other Status Code from API HTTP response status codes have so much importance in REST API’s. In any case if you want to return a status code from your ASP.NET Core API, all you have to do is in your controller method,