How does ASP.NET Core WebApi return XML data format
This article mainly introduces ASP.NET Core WebApi how to return XML data format, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
First, ask questions
ASP.NET Core WebAPI returns XML data format, but also need you, stupid, you to explain to everyone? We all understand and understand this, so the question is really like this? Aren't you just setting Accept to application/xml?
This is explained by the WeatherForecastController example in the ASP.NET Core default API project. After experiments, it is found that the test results are not what we expected. The following figure still returns the JSON format.
Second, analyze the problem
When working on webapi projects, Asp.net core only returns data in json format by default. If you want to enable xml data return, you need to configure it in startup as follows:
This allows you to control the format of the data that the request needs to return through head's accept.
If you don't want to set accept to the application/xml parameter every time you request, we can add the feature [Produces ("application/xml")] to the specified controller here.
You think that's it? If you are careful, you may find that you may encounter strange problems when converting to xml formatting. There are a lot of xmlns:xsi namespaces in xml format for no reason, so how to remove namespaces from xml format?
The online article says that the reason for this problem is that multiple objects that return results are not under the same namespace and can be solved by putting them in the same namespace. So is the problem really solved in this way?
Third, solve the problem
Customize the XmlSerializerOutputFormatter class to remove namespaces from XML serialization.
IV. Download the source code
Thank you very much for the support for [playing NET with Aben]. If you have any questions, the official account of Wechat replied to the wx keyword and added Aben's personal WeChat account.
"ASP.NET Core WebApi how to return XML data format" source code download follow official account, reply keyword: ch4e
Tencent Classroom
NetEase Yun classroom
Thank you for reading this article carefully. I hope the article "how to return ASP.NET Core WebApi to XML data format" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!