我有这样的API响应:
<MYAPI xsi:noNamespaceSchemaLocation="MYAPI.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SomeTask LastModified = "Some Date" Resource="Some Resource Name">
<Name>Some Name</Name>
<ID>Some ID</ID>
</SomeTask>
... A lot of these <SomeTask>...</SomeTask> are there
</MYAPI>
我已经将类建模为:
XmlRoot(ElementName = "MYAPI")]
class MYAPI
{
[XmlElement(ElementName = "SomeTask")]
public List<SomeTask> SomeTask{ get; set; }
}
[XmlRoot(ElementName="SomeTask")]
public class SomeTask {
[XmlElement(ElementName="Name")]
public string Name { get; set; }
[XmlElement(ElementName="ID")]
public string ID { get; set; }
[XmlAttribute(AttributeName="LastModified")]
public string LastModified { get; set; }
[XmlAttribute(AttributeName="Resource")]
public string Resource { get; set; }
}
我正在尝试这样阅读它:
static void Main()
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("MyUsername", "MyPassword");
var client = new HttpClient(handler);
client.BaseAddress = new Uri("https://sitename.com:PortNumber/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var formatters = new List<MediaTypeFormatter>()
{
new XmlMediaTypeFormatter(){ UseXmlSerializer = true }
};
var myApi = new MYAPI();
HttpResponseMessage response = client.GetAsync("/api/mysites/tasks").Result;
if (response.IsSuccessStatusCode)
{
myApi = response.Content.ReadAsAsync<MYAPI>(formatters).Result;
}
}
但是使用此代码,我总是会遇到以下异常:
No MediaTypeFormatter is available to read an object of type 'MYAPI' from content with media type 'application/xml'.
有人可以告诉我如何解决这个问题吗?谢谢!