I'm new to asp.net core 3, sorry if my question sounds too basic, below is my controller class:
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase {
List<string> _fruit = new List<string> { "Pear", "Lemon", "Peach" };
[HttpGet("fruit")]
public IEnumerable<string> MethodXXX() {
return _fruit;
}
...
}
so when I route to my/fruit
, I get a list of string.
But if I change the MethodXXX to :
[HttpGet("fruit")]
public IEnumerable<string> MethodXXX() {
return null;
}
Then the browser always fall back to the previous url, e.g I'm on my/other
in the beginning, then I change the url to my/fruit
, I can see that the browser sends a new request and the url changes to my/fruit
for a short period of time then it fall back to my/other
again.
What is this behavior for? I am pretty sure I read from a book which says that you can return null from action method?
This is a behavior newly introduced in .Net Core 3 where if the Action method returns null, it just sends a 204 response which represents No Content. If you desire to return null from an action method, you can override this behavior by using below code block inside Startup.cs file which removes the corressponding Output formatter and you will get null returned from the API response.
services.AddControllers(options =>
{
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With