This article is a mirror article of machine translation, please click here to jump to the original article.

View: 3324|Reply: 0

[Source] ASP.NET Core(23) API interface NULL returns HTTP 204 status code

[Copy link]
Posted on 8/20/2023 3:27:55 PM | | | |
Requirements: Use ASP.NET Core 6 to create a new Web API project to provide external services, the interface may return an empty object or an empty string, if it returns NULL, the interface response is: 204 No Content, although 204 represents the normal response code (there is nothing wrong with it), but,Some encapsulated HTTP frameworks will only consider the 200 status code to be normal。 So change the 204 status code to a 200 status code.

Interface code:

The test is shown below:



The interface returns an HTTP 204 No Content status code because of the 4 output-formatting implementations added by default in ASP.NET Core:

  • Microsoft.AspNetCore.Mvc.Formatters.HttpNoContentOutputFormatter
  • Microsoft.AspNetCore.Mvc.Formatters.StringOutputFormatter
  • Microsoft.AspNetCore.Mvc.Formatters.StreamOutputFormatter
  • Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter


The source code for HttpNoContentOutputFormatter is as follows:



Note:If the interface returns a void type, Task returns an HTTP 200 status codebecause it does not go into the CanWriteResult method in HttpNoContentOutputFormatter!! thereintoIf the CanWriteResult method returns true, it will go through WriteAsyncMethod.





solution

Remove the HttpNoContentOutputFormatter implementation class from the OutputFormatters collection with the following code:

Access the interface again, test as follows:

The return type is string?, returns a 200 status code, and does not have any output
The return type is object?, returns a 200 status code, and outputs null

(End)




Previous:The Docker container is based on aspnet:6.0 to install the ping tool
Next:Windows Edge browser opens crash solution with IE
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com