I am trying to emulate a server I don't have access to for testing. The server returns the contents of XML files that the client I am testing reads and loads into XmlDocument classes. It seems like it should be easy to read an xml file and return its contents but I can't seem to figure it out. If I load the file into an XmlDocument and return the InnerXML, the controller wraps the result in a root and the XmlDocument on the client balks at it.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><?xml version="1.0" encoding="utf-8"?><credential xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><user>User</user><password>Password</password><cookie>Cookie Text</cookie><site xmlns="vs">VS Site</site><funcList>func1, func2, func3</funcList></credential></string>
If I try to return the XmlDocument the controller throw an exception: 'System.Xml.XmlDocument' is an invalid collection type since it does not have a valid Add method with parameter of type 'System.Object'.
using Newtonsoft.Json;
using POSComWebTest.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
namespace WshhWebApi.Controllers
{
[RoutePrefix("SiteController")]
public class AuthorizeController : ApiController
{
[Route("cgi-bin/CGILink")]
[HttpGet]
public IHttpActionResult CGILink(string cmd, string user, string passwd)
{
try
{
string file = Path.Combine(HttpContext.Current.Server.MapPath("~"), "App_Data", "credential.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(file);
HttpContext.Current.Response.ContentType = "application/xml";
//return Content(System.Net.HttpStatusCode.OK, xmlDoc.InnerText); // garbage
return Content(System.Net.HttpStatusCode.OK, xmlDoc.InnerXml); // <string root> client can't read as xml
//return Content(System.Net.HttpStatusCode.OK, xmlDoc); // 'System.Xml.XmlDocument' is an invalid collection type since it does not have a valid Add method with parameter of type 'System.Object'.
}
catch (Exception ex)
{
return BadRequest($"CGILink Failed: {ex.Message}");
}
}
}
}
It seems like this should be easy and I hope I just haven't Googled the wrong questions. Thanks!
Oh, here is my XML file credential.xml:
<?xml version="1.0" encoding="utf-8"?>
<credential xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<user>User</user>
<password>Password</password>
<cookie>Cookie Text</cookie>
<site xmlns="vs">VS Site</site>
<funcList>func1, func2, func3</funcList>
</credential>
Firstly I want to thank everybody for their answers! I think I figured it out. If I just download the file as 'application/octet-stream' the client is able to turn this into an XmlDocument. I really did not think it would work but I have spent too much time on this and am getting desperate. Below was my solution:
Thanks again to everyone who responded.