[英]Why returning null does nothing in web api project?
I'm new to asp.net core 3, sorry if my question sounds too basic, below is my controller class:我是 ASP.NET Core 3 的新手,抱歉,如果我的问题听起来太基本了,下面是我的控制器类:
[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.所以当我路由到
my/fruit
,我会得到一个字符串列表。
But if I change the MethodXXX to :但是,如果我将 MethodXXX 更改为:
[HttpGet("fruit")]
public IEnumerable<string> MethodXXX() {
return null;
}
Then the browser always fall back to the previous url, eg 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.然后浏览器总是回退到之前的 url,例如我一开始在
my/other
上,然后我将 url 更改为my/fruit
,我可以看到浏览器发送了一个新请求并且 url 更改为my/fruit
一小段时间然后它又回到my/other
身上。
What is this behavior for?这种行为是为了什么? I am pretty sure I read from a book which says that you can return null from action method?
我很确定我从一本书中读到过,它说你可以从 action 方法返回 null?
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.这是 .Net Core 3 中新引入的一种行为,如果 Action 方法返回 null,它只会发送一个 204 响应,表示无内容。 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.
如果您希望从操作方法返回 null,您可以使用 Startup.cs 文件中的以下代码块覆盖此行为,该文件删除相应的输出格式化程序,您将从 API 响应中返回 null。
services.AddControllers(options =>
{
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});
you most changed你变化最大
[HttpGet]
[ActionName("fruit")]
public IEnumerable<string> MethodXXX() {
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.