简体   繁体   English

如何在 ASP.NET MVC 中使用 ActionResult 返回带有声明的 Xml?

[英]How do I return Xml with declaration using an ActionResult in ASP.NET MVC?

I'm unable to attach a xml declaration while returning xml using Action Result.我无法在使用 Action Result 返回 xml 时附加 xml 声明。 I can see it being included while debugging till line at which it returns xml in below code but doesn't not show up on the web.我可以看到它在调试时被包含在内,直到它在下面的代码中返回 xml 但没有显示在网络上。

What I am doing currently:我目前在做什么:

  1. Getting Xml from Sql Server using XML PATH.使用 XML PATH 从 Sql Server 获取 Xml。
  2. Returning xml string using XML Reader :使用XML Reader返回 xml 字符串:

     public XmlDocumentResult XmlData() { String s = "<?xml version=\\"1.0\\" encoding=\\"utf-8\\" ?>" + "\\n" + this.GetData(); byte[] encodedString = Encoding.UTF8.GetBytes(s); MemoryStream ms = new MemoryStream(encodedString); ms.Flush(); ms.Position = 0; XmlDocument doc = new XmlDocument(); doc.Load(ms); return new XmlDocumentResult { XmlDocument = doc }; } public class XmlDocumentResult : ContentResult { public XmlDocument XmlDocument { get; set; } public override void ExecuteResult(ControllerContext context) { if (XmlDocument == null) return; Content = XmlDocument.OuterXml; ContentType = "text/xml"; base.ExecuteResult(context); } }

I have tried following code snippets from Stackoverflow:我尝试过以下 Stackoverflow 中的代码片段:

XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);


XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);

Maybe try this:也许试试这个:

public IActionResult Index()
{
    // you need to convert your xml to string
    var xmlString = "xml content..";
    return this.Content(xmlString, "text/xml");
}

See https://docs.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd492713%28v%3dvs.100%29请参阅https://docs.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd492713%28v%3dvs.100%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM