top of page
Writer's pictureThe Tech Platform

Handling Null Values in ASP.NET Core



ASP.NET Core MVC is the .NET Core counterpart of the ASP.NET MVC framework. You can take advantage of ASP.NET Core MVC to build cross-platform, scalable, high-performance web applications and APIs using the Model-View-Controller design pattern.


First, create a new ASP.NET Core project in visual studio. Here we will handle null values in ASP.NET Core MVC


Create new Controller

In the Solution Explorer window, select the Controllers folder in the project, then right-click and choose Add->Controller to create a new controller. Specify the name of the controller class as DemoController. Next, replace the code of the DemoController class with the following code.

[Route("api/[controller]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        readonly Repository repository = new Repository();
        [HttpGet]
        public ActionResult Get()
        {
            string item = repository.GetMessage();
            return Ok(item);
        }
        [HttpGet("{id}", Name = "Get")]
        public IActionResult Get(int id)
        {
            string item = repository.GetMessage();
            return Ok(item);
        }
    }

Repository Class

Here is a dummy version of the Repository class that contains just one method that returns null. Of course this is only for illustrative purposes.

public class Repository
    {
        public string GetMessage()
        {
            return null;
        }
    }

Handling Null Value

When you call the HttpGet endpoint of the DemoController shown above, the out-of-box behavior of ASP.NET Core MVC is to reply with HTTP Status Code 2014, i.e. “No Content,” as shown in the screen image given below.


When sending back a response, the ASP.NET Core MVC framework attempts to select an output formatter from among the available formatters to handle the response object. Typically, this formatter can be a JSON formatter, an XML formatter, or any formatter appropriate to the media type.


However, when handling null values, the framework uses a different formatter. This formatter, called HttpNoContentOutputFormatte, is responsible for converting the null responses to HTTP Status Code 204, or the “No Content” response.


Disable the HttpNoContentOutputFormatter

You can disable the default null value handling behavior in ASP.NET Core MVC by disabling the HttpNoContentOutputFormatter.


To do this, write the following code in the ConfigureServices method in the Startup class.

services.AddMvc(f =>
  {
      f.OutputFormatters.RemoveType
      (typeof(HttpNoContentOutputFormatter));
      f.OutputFormatters.Insert(0, new
      HttpNoContentOutputFormatter
      {
          TreatNullValueAsNoContent = false
      });
});

This will disable the HTTP Status Code 204 behavior. The response will now be HTTP Status Code 200, i.e. “OK,” with a null value written to the response object.


Return HTTP Status Code 404

Let’s update the controller’s action methods to return HTTP Status Code 404. Here is the updated version of the DemoController for your reference.

[Route("api/[controller]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        readonly Repository repository = new Repository();
        [HttpGet]
        public ActionResult Get()
        {
            string item = repository.GetMessage();
            if (item == null)
                return NotFound();
            return Ok(item);
        }      
    }

When you run the action method this time, HTTP Status Code 404, i.e. “Not Found,” is returned as shown in the screen image below.




Resource: infoworld.com


The Tech Platform

0 comments

Recent Posts

See All

Comments


bottom of page