.Net Core XmlDocument不返回声明

时间:2019-01-09 17:42:57

标签: c# xml asp.net-core .net-core xmldocument

我有一个带有XmlDocument的.net核心Web应用程序,即使不进行任何修改也不会返回声明。

我有这个代码

[HttpPost]
[Consumes("application/xml")]
[Produces("application/xml")]
public ActionResult<XmlDocument> GW1()
{
    XmlDocument xmlDocRec = new XmlDocument();
    xmlDocRec.Load(Request.Body);
    return Ok(xmlDocRec);
}

请求

<?xml version="1.0" encoding="utf-8"?>
<GR User="User1" PropertyCode="90001045">
    <GW>1</GW>
</GR>

响应

<GR User="User1" PropertyCode="90001045">
    <GW>1</GW>
</GR>

我在启动中有这个

services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddXmlSerializerFormatters();

我需要回复<?xml version="1.0" encoding="utf-8"?>,但我不知道为什么它不返回。在xmlDocRec.InnerXml和xmlDocRec.OuterXml中存在。

我既没有将其归类为参数,也没有响应,我无法将其用于需求,因为我使用了Request.Body

很显然,我使用xmlDocRec,添加和更新了元素,但是结果是相同的。当我使用xmlDocRec时,xmlDocRec.InnerXml和xmlDocRec.OuterXml包含<?xml version="1.0" encoding="utf-8" standalone="no"?>。稍后,我将需要删除standalone =“ no”,因为它不能作为响应。

---编辑

我不知道这是否是严格的方法,但是现在我正在使用它

[HttpPost]
public ContentResult GW1()
{
    XmlDocument xmlDocRec = new XmlDocument();
    xmlDocRec.Load(Request.Body);

    return new ContentResult
    {
        ContentType = "application/xml",
        Content = xmlDocRec.OuterXml,
        StatusCode = 200
    };
}

有了这个,我不需要在启动时使用Consumes,Produces和AddXmlSerializerFormatters。

如果有人知道更好的方法,我愿意尝试。

2 个答案:

答案 0 :(得分:0)

您可能希望使用在XmlDeclaration类上设置的显式属性值来制作响应。

  

我建议您看看XmlDeclaration Class

[HttpPost]
[Consumes("application/xml")]
[Produces("application/xml")]
public ActionResult<XmlDocument> EchoXmlAndChangeEncoding()
{
    string requestXML = Request.Body;

    XmlDocument doc = new XmlDocument();
    doc.Load(new StringReader(requestXML));

    // Grab the XML declaration. 
    XmlDeclaration xmldecl = doc.ChildNodes.OfType<XmlDeclaration>().FirstOrDefault();
    xmldecl.Encoding = "UTF-8";
    xmldecl.Standalone = null;   // <-- or do whatever you need

    ... // set other declarations here

    // Output the modified XML document 
    return Ok(doc.OuterXml);
}

答案 1 :(得分:0)

您可以尝试使用XmlWriterSettings.OmitXmlDeclaration在ConfigureServices方法中配置XmlSerializerOutputFormatter,并将其设置为false,因为默认情况下将其设置为true。

private void ConfigureXmlOutpuFormatter(MvcOptions options)
{
     XmlWriterSettings settings = new XmlWriterSettings
     {
       OmitXmlDeclaration = false
     };
     options.OutputFormatters.Add(new XmlSerializerOutputFormatter(settings));
}