Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error status in JsonResult in Asp.Net Core?

I am trying to return the error status after migrating an Asp.Net MVC 5 application to the Core version.

In my old application I used a class (JsonHttpStatusResult) that inherits from JsonResult and returned a catch error if any. However, when trying to add this to the new project, unfortunately it no longer has some features.

I would like to use this same concept for the Asp.Net Core version because I don't want to return a true or false if an error occurs in JsonResult. The following is an example of how it worked in the MVC 5:

CLASS:

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);
    }
}

EXAMPLE ON JSONRESULT:

public JsonResult Example()
{
    try
    {
        //Some code
        return Json(/*something*/);
    }
    catch (Exception ex)
    {
        return new JsonHttpStatusResult(ex.Message, HttpStatusCode.InternalServerError);
    }
}

AJAX REQUEST:

$.ajax({
    url: "/Something/Example",
    type: "POST",
    dataType: "json",
    success: function (response) {
        //do something
    },
    error: function (xhr, ajaxOptions, thrownError) {
         //Show error
    }
});

How to do this or something similar in Asp.Net Core?

like image 246
Leomar de Souza Avatar asked Sep 06 '25 05:09

Leomar de Souza


1 Answers

You don't have to create you own implementation in ASP.NET Core.

ASP.NET Core introduces a new StatusCode Property for JsonResult class.

So simply change your code to :

catch (Exception ex)
{
    return new JsonResult(ex.Message){
        StatusCode = (int)HttpStatusCode.InternalServerError
    };
}
like image 154
itminus Avatar answered Sep 09 '25 05:09

itminus