我想从rest api请求返回一个xml文档:
[HttpPost]
public string getClassXml(HttpRequestMessage req)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
ClassXML classid = new ClassXML();
XmlDocument doc = new XmlDocument();
try
{
var data = req.Content.ReadAsStringAsync().Result;
classid = serializer.Deserialize<ClassXML>(data.ToString().Trim());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
string path = ASDb.ReadValue("SELECT definitionxml FROM alclass WHERE classid='" + classid.classID + "'").ToString();
XmlTextReader reader = new XmlTextReader(AppDomain.CurrentDomain.BaseDirectory + "Resource\\" + percorso);
reader.Read();
doc.Load(reader);
return doc.innerXml;
}
但是这样我得到一个字符串,我想让XmlDocument不是一个字符串。我也尝试返回XmlDocument文档,但它给了我一个错误:他&#39; ObjectContent`1&#39;类型无法序列化内容类型&#39; application / xml的响应正文;字符集= UTF-8&#39 ;. 你有什么想法吗?
答案 0 :(得分:4)
正如有人在几秒钟之前在这里写的那样(但后来删除了他的回答)问题是XmlDocument不可序列化,如果你使用XmlElement就可以了。这是我做的:
[HttpPost]
public XmlElement getClassXml(HttpRequestMessage req)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
ClassXML classid = new ClassXML();
XmlDocument doc = new XmlDocument();
try
{
var data = req.Content.ReadAsStringAsync().Result;
classid = serializer.Deserialize<ClassXML>(data.ToString().Trim());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
string path = ASDb.ReadValue("SELECT definitionxml FROM alclass WHERE classid='" + classid.classID + "'").ToString();
XmlTextReader reader = new XmlTextReader(AppDomain.CurrentDomain.BaseDirectory + "Resource\\" + percorso);
reader.Read();
doc.Load(reader);
XmlElement element = doc.DocumentElement;
return element;
}
答案 1 :(得分:1)
也许问题不在于您的API图层,而是在您尝试使用XmlTextReader的时候?
XmlTextReader reader = new XmlTextReader(AppDomain.CurrentDomain.BaseDirectory + "Resource\\" + percorso);
您尝试阅读的XML是什么样的?你检查过它是否形成良好?
就&#34;使用REST API&#34;返回XML文档而言,我建议您只需将XML文档作为具有相应MIME类型的字符串输出,执行以下操作:
[HttpPost]
public HttpResponseMessage getClassXml(HttpRequestMessage req)
{
...
XmlTextReader reader = new XmlTextReader(AppDomain.CurrentDomain.BaseDirectory + "Resource\\" + percorso);
reader.Read();
doc.Load(reader);
HttpResponseMessage response = new HttpResponseMessage { Content = new StringContent(doc.innerXml, Encoding.UTF8,"application/xml") };
return response;
}
REST API输出应映射到标准的互联网mime类型(例如JSON数据,图像,文本等 - 而不是XmlDocument)。无论您使用什么样的REST API,只需获取文本并在必要时将其转换为XmlDocument。
顺便说一下,你似乎甚至没有使用你提供的示例中的一半代码,你可以清理它:
string path = ASDb.ReadValue("SELECT definitionxml FROM alclass WHERE classid='" + classid.classID + "'").ToString();
答案 2 :(得分:0)
很抱歉,如果我现在想要从HttpPost更改为HttpGet,我将如何获取以下网址中的参数:http://localhost/arcosat/api/ws/GetClassXml?classid=myclass
我想得到&#34; myclass&#34;字符串,但req.Content.ReadAsStringAsync().Result
它不再起作用