我有这个 WebAPI,我正在尝试将 xml 数据返回给客户端。
[HttpGet]
public IEnumerable<XElement> GetPersons(string name)
{
var doc = XDocument.Load(path);
var result = doc.Element("Persons")
.Elements("Person")
.Where(x => (string)x.Element("name") == name);
return result();
}
直接调用数据(http://localhost:63068/api/GetPersons/b
):
<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfXElement xmlns="http://schemas.datacontract.org/2004/07/System.Xml.Linq" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<XElement>
<Person xmlns="">
<PersonID>1</PersonID>
<Name>b</UserName>
</Person>
</XElement>
<XElement>
<Person xmlns="">
<PersonID>2</PersonID>
<Name>b</UserName>
</Person>
</XElement>
</ArrayOfXElement>
从客户端调用服务时出错:
$.ajax({
url: baseURL + 'GetPersons/' + $('#txtUserName2').val(),
type: "GET",
success: function (result) {
divResults.html(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
divResults.html(err);
}
});
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"An item with the same key has already been added.","ExceptionType":"System.ArgumentException","StackTrace":" at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)\r\n
我究竟做错了什么?