我需要将包含根节点中前缀的xml发布到控制器。这是我需要发布的xml:
<?xml version="1.0" encoding="UTF-8"?>
<star:SecuredFiles xmlns:star="http://www.starstandard.org/STAR/5">
<ED>2019-05-07T16:39:13Z</ED>
<AID/>
<SNC>U8</SNC>
<SID>sample</SID>
<RID>F37C6B44-FCA3-4313-A1E3-42EDB131FD17</RID>
<FileURI>9928645r01.pdf</FileURI>
<ServerGuid>PRUCTIONS</ServerGuid>
</star:SecuredFiles>
在控制器上,我的代码如下:
[HttpPost]
public async Task<IActionResult> Post([FromBody]SecuredFiles secureFile)
{
----------
}
我有类似这样的模型类:
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.starstandard.org/STAR/5")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.starstandard.org/STAR/5", IsNullable = false)]
public class SecuredFiles
{
public DateTime ED { get; set; }
public string AID { get; set; }
public string SNC { get; set; }
public string SID { get; set; }
public string RID { get; set; }
public string FileURI { get; set; }
public string ServerGuid { get; set; }
}
现在,当我尝试将此xml发布到控制器时,属性中的值为空。
我的Startup.cs看起来像:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(opt =>
{
opt.Filters.Add(typeof(ValidateModelStateAttribute)); // by type
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
------
}
请有人帮忙进行修复。
谢谢
答案 0 :(得分:0)
我已通过在控制器上使用此方法解决了此问题。
var body = string.Empty;
SecuredFiles secureFile = new SecuredFiles(); ;
Request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(Request.Body))
{
body = reader.ReadToEnd();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(body);
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("star", "http://www.starstandard.org/STAR/5");
string xpath = "star:SecuredFiles";
var nodes = xmlDoc.SelectNodes(xpath, nsmgr);
// Read data from STAR xml
foreach (XmlNode childrenNode in nodes)
{
secureFile.AID = childrenNode.SelectSingleNode("//AID").InnerText;
secureFile.ED = childrenNode.SelectSingleNode("//ED").InnerText;
secureFile.FileURI = childrenNode.SelectSingleNode("//FileURI").InnerText;
secureFile.RID = childrenNode.SelectSingleNode("//RID").InnerText;
secureFile.ServerGuid = childrenNode.SelectSingleNode("//ServerGuid").InnerText;
secureFile.SID = childrenNode.SelectSingleNode("//SID").InnerText;
secureFile.SNC = childrenNode.SelectSingleNode("//SNC").InnerText;
}
谢谢