In previous article, I have explained about jQuery AJAX in ASP.NET Core MVC, now in this article, we will see how to return JSONResult With Status code in ASP.NET Core MVC.

Step 1: Open your Visual Studio (2017 or 2019 version), search select "Create a New Project" and search for "ASP.NET Core MVC web-application" as shown in the below image

asp-net-core-json-result-post-min.png

Step2: Now, let's configure JSON in our ASP.NET Core MVC project, by navigating to Startup.cs, and use the code in ConfigureServices

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
        }

You will also have to add reference for 'using Newtonsoft.Json.Serialization;'

Step 3: We will create Student.cs Model in Models folder of project, so right-click on Models folder and then select "Add" -> then select "Class" -> then add new class with name Student.cs

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Step 4: Navigate to HomeController.cs, where we will create two methods to return JSON response with results

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace JSONResultASPNETCore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetAsJson()
        {
            //return json with 200 OK status code (it's an Ok type of ObjectResult)
            return new OkObjectResult(new Student { Id = 123, Name = "Hero" });
        }

        [Produces("application/json")]
        public Student GetWithProduces()
        {
            // does the same as above method by using Produces() attribute (which is a ResultFilter) with contentType = application/json
            return new Student { Id = 123, Name = "Hero" };
        }


        public IActionResult ErrorJSON()
        {
            //return json with 400 error code with message
            return new JsonResult(new { message = "Error Messages" })
            {
                StatusCode = StatusCodes.Status400BadRequest // Status code here 
            };
        }

    }
}

I have commented out important part of code, but I will explain important points here.

Basically, we have created two methods, which are returning JSON results

  • OkObjectResult: returns with 200 OK status code (it's an Ok type of ObjectResult)
  • Second method (GetWithProduces) return same results but by using Produces() attribute (which is a ResultFilter) with contentType = application/json
  • In third method, we are return JSON Result with error response, that is 400 bad request, just for demo prupose, basically in third method you can see we can pass status code explicitly.

Step 5: We are almost done, we need to navigate to Views -> Home -> Index.cshtml and use the below code, to check JSON returned with response here

@{
    ViewData["Title"] = "Home Page";
}
<br />
<input type="text" id="txtName" placeholder="Student Name" />
<input type="button" id="btnGet" value="Get Student name using JSON" class="btn btn-primary" />
<br/>
<br />
<input type="text" id="error" placeholder="Error Message" />
<input type="button" id="erroBtn" value="Get Error Status With JSON" class="btn btn-primary" />

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "GET",
                    url: "/home/GetAsJson",
                    success: function (response) {
                        $("#txtName").val(response.Name);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });

            $("#erroBtn").click(function () {
                $.ajax({
                    type: "GET",
                    url: "/home/ErrorJSON",
                    success: function (response) {
                        //it will not be returned  here since we are returning status code 400
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        //respone will be returned here
                        $("#error").val(response.responseText);
                    }
                });
            });
        });
    </script>

}

Once we are done, We can check output by clicking on the Buttons of Page.

You will see we are getting JSON response with status code 200 and 400 for requests, after clicking on buttons one by one.

Here is the demo gif

json-result-asp-net-core-mvc-min.gif

So, as you can see in the above GIF, we can easily get JSON result with status code in ASP.NET Core MVC, hope this helps.

You may also like to read:

How to read JSON data in C# (Example using Console app & ASP.NET MVC)?

Resize image in C# (Console application example)

Encrypt and Decrypt files in C#

Get Vs post in Rest API