这两天对接第三方系统,需要接收及返回xml的数据,采用WebApi来进行处理,使用post来传输数据,
记得查看WebApiConfig中的Register方法里有没有将xmlFormatter移除
代码如下:
[HttpPost]
public HttpResponseMessage PunchoutRequest()
{
try
{
PunchOutSetupRequest punchoutRequest = new PunchOutSetupRequest();
//接收到xml数据并用XDocument加载
XDocument xd = XDocument.Load(Request.Content.ReadAsStreamAsync().Result);
#region 解析收到的XML并存入实体类中
//填充Header中的数据
List<XElement> fromCredentialNodes = xd.Root.Element("Header").Element("From").Elements().ToList();
AribaPunchoutMessageFunc.SetHeaderInfoToDTO(punchoutRequest, fromCredentialNodes, "From");
List<XElement> toCredentialNodes = xd.Root.Element("Header").Element("To").Elements().ToList();
AribaPunchoutMessageFunc.SetHeaderInfoToDTO(punchoutRequest, toCredentialNodes, "To");
List<XElement> senderCredentialNodes = xd.Root.Element("Header").Element("Sender").Elements().ToList();
AribaPunchoutMessageFunc.SetHeaderInfoToDTO(punchoutRequest, senderCredentialNodes, "Sender");
//填充Request中的数据
XElement RequestRoot = xd.Root.Element("Request").Element("PunchOutSetupRequest");
AribaPunchoutMessageFunc.SetRequestInfoToDTO(punchoutRequest, RequestRoot);
//将发过来的请求信息保存起来
AribaPunchoutMessageFunc.BuyerRequest = punchoutRequest;
#endregion
//读取Response文档模板并赋值
XmlDocument xd2 = new XmlDocument();
xd2.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ResponseTemplate.xml"));
AribaPunchoutMessageFunc.SetResponseCXML(xd2);
//返回一个流。里面保存xml数据
HttpResponseMessage result;
using (MemoryStream stream = new MemoryStream())
{
xd2.Save(stream);
result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
}
return result;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
}