Null response returns a 204

With the new ActionResult<T> in v2.1+ you can also refactor to specifically tell the controller to return Ok 200 using the Ok() helper methods

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        return Ok(model);
    }
}

however this can be misleading if there is in fact no content to return. Consider using an appropriate response status

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        if(model == null) return NotFound(); //404
        return Ok(model); //200
    }
}

If intent on returning 200 Ok with no content use ControllerBase.Ok() method

Creates a OkResult object that produces an empty Status200OK response.

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        if(model == null) return Ok(); //200 with no content
        return Ok(model); //200
    }
}

Reference Controller action return types in ASP.NET Core Web API:


See:

  • https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1#special-case-formatters
  • https://www.colabug.com/2020/0224/7036191/
  • https://weblog.west-wind.com/posts/2020/Feb/24/Null-API-Responses-and-HTTP-204-Results-in-ASPNET-Core

services.AddControllers(opt =>  // or AddMvc()
{
    // remove formatter that turns nulls into 204 - No Content responses
    // this formatter breaks Angular's Http response JSON parsing
    opt.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
})