4

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?

1 Answer 1

8

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
    };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.