C# 使用';将XML粘贴为类';反序列化Web API rest响应的步骤
我在使用VS2012中的“将XML粘贴为类”功能时遇到问题,无法使用Web API正确地反序列化Rest调用的XML结果 调用的XML响应如下所示:C# 使用';将XML粘贴为类';反序列化Web API rest响应的步骤,c#,asp.net-mvc,asp.net-web-api,xml-serialization,deserialization,C#,Asp.net Mvc,Asp.net Web Api,Xml Serialization,Deserialization,我在使用VS2012中的“将XML粘贴为类”功能时遇到问题,无法使用Web API正确地反序列化Rest调用的XML结果 调用的XML响应如下所示: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <SCResponse> <AccountId>86</AccountId> <Administrator>false</Administrator>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SCResponse>
<AccountId>86</AccountId>
<Administrator>false</Administrator>
<Email>6z@z.com</Email>
<FirstName>6z@z.com</FirstName>
<Label>false</Label>
<LastName>6z@z.com</LastName>
<link href="https://cnn.com" rel="news" title="News"/>
</SCResponse>
我这样称呼REST端点:
string path = String.Format("account/{0}", id);
HttpResponseMessage response = client.GetAsync(path).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
account = response.Content.ReadAsAsync<Models.account.response.Account>().Result;
}
处理这个问题的一个更简单的方法可能是使用,它将为您完成所有的反序列化。这将简化您的调用,并且您不需要模型上的XML属性 请看下面一个使用RestSharp进行aync调用的好例子:
希望这能有所帮助。在使用[DataContract]时,是否需要将[DataMember]属性添加到每个属性中。。。
string path = String.Format("account/{0}", id);
HttpResponseMessage response = client.GetAsync(path).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
account = response.Content.ReadAsAsync<Models.account.response.Account>().Result;
}
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;