Sometimes in an MVC controller you just want to return a HTTP status code from a method rather than a view or data object. This is pretty simple but is done slightly differently in .NET Core than it was done previously.

Some of the more common status codes such as OK (200), and Not Found (404) have shortcut methods which can be returned like so.

public class HomeController : Controller
{
	public IActionResult LogFilterChange()
	{
		// Code here... return Ok();
	}
}

Status codes without such a shortcut method as well as custom ones can also be returned through the StatusCode method which takes an integer as an input, an enum of standard status codes can be found in StatusCodes.

public class HomeController : Controller
{
	public IActionResult LogFilterChange()
	{
		// Code here...
		return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status204NoContent);
	}
}

Along with the status code objects can also be returned by the StatusCode method which will serialize the provided object into whatever form the caller requested (JSON by default).

public class HomeController : Controller
{
	public IActionResult LogFilterChange()
	{
		// Code here...
		MyObject myObject = new MyObject();
		myObject.Name = "Message Object";
		myObject.Message = "Hello from the object!";
		
		return Ok(myObject);
	}
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *