102*_*074 2 c# .net-core asp.net-core
这是我的代码:
[HttpPost]
[Produces("application/xml")]
public async Task<xml> mp([FromBody]xml XmlData)
{
xml ReturnXmlData = null;
ReturnXmlData = new xml()
{
ToUserName = XmlData.FromUserName,
FromUserName = XmlData.ToUserName,
CreateTime = XmlData.CreateTime,
MsgType = "text",
Content = "Hello world"
};
return ReturnXmlData;
}
[XmlRoot("xml")]
public class xml
{
public string ToUserName { get; set; }
public string FromUserName { get; set; }
public string CreateTime { get; set; }
public string MsgType { get; set; }
public string MsgId { get; set; }
public string Content { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在,在我将这些代码发布到本地服务器进行测试之后:
<xml>
<ToUserName>123</ToUserName>
<FromUserName>45</FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>text</MsgType>
<Content>greating</Content>
</xml>
Run Code Online (Sandbox Code Playgroud)
然后它会返回这些:
<xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ToUserName>45</ToUserName>
<FromUserName>123</FromUserName>
<CreateTime>20190921203758</CreateTime>
<MsgType>text</MsgType>
<Content>Hello world</Content>
</xml>
Run Code Online (Sandbox Code Playgroud)
嗯,如你所见。XML 数据包含远程服务器中不允许的 xmlns:xsi 和 xmlns:xsd。
此外,远程服务器不受我们控制,我无法更改任何代码或任何规则。
这意味着我必须像这样修改返回的 XML:
<xml>
<ToUserName>45</ToUserName>
<FromUserName>123</FromUserName>
<CreateTime>20190921203758</CreateTime>
<MsgType>text</MsgType>
<Content>Hello world</Content>
</xml>
Run Code Online (Sandbox Code Playgroud)
返回 XML 时如何删除 xmlns:xsi 和 xmlns:xsd?谢谢你。
您可以为 xml 创建自定义序列化程序格式化程序,并且可以从默认XmlSerializerOutputFormatter实现继承它
public class XmlSerializerOutputFormatterNamespace : XmlSerializerOutputFormatter
{
protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
{
//applying "empty" namespace will produce no namespaces
var emptyNamespaces = new XmlSerializerNamespaces();
emptyNamespaces.Add("", "any-non-empty-string");
xmlSerializer.Serialize(xmlWriter, value, emptyNamespaces);
}
}
Run Code Online (Sandbox Code Playgroud)
添加此格式化程序 Startup
services
.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace());
})
//there should be one of the following lines in your application already in order to make xml serialization work
//our custom output formatter will override default one since it's iterated earlier in OutputFormatters collection
.AddXmlSerializerFormatters()
//.AddXmlDataContractSerializerFormatters()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1757 次 |
| 最近记录: |