![](/img/trans.png)
[英]How to upload files to Asp.Net MVC 4.0 action running in IIS Express with HttpClient class included in .Net 4.0
[英]How to parse XML response using HttpClient in .Net 4.0 to .Net Class?
我有一個返回xml作為響應的Web服務。
下面是xml響應的屏幕截圖:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Header>
<Message type="String"></Message>
</Header>
<Output>
<Rows>
<Row>
<Result type="Integer">1021806</Result>
</Row>
</Rows>
</Output>
</Root>
這是我的.net模型,代表xml響應:
public class ResponseModel
{
public class Root
{
public Header header { get; set; }
public Output output { get; set; }
}
public class Header
{
public string Message { get; set; }
}
public class Output
{
public List<Row> Rows { get; set; }
}
public class Row
{
public int Result { get; set; }
}
}
我正在使用HttpClient
類將請求發送到指定的Web服務。
這是我的代碼:
using (var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
var response = client.GetAsync("myWebServiceUrl").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
}
}
responseContent
有三種方法:
ReadAsStringAsync()
ReadAsStreamAsync()
ReadAsByteArrayAsync()
三種方法有什么區別?
我應該使用哪一個進行xml響應,以及如何將xml解析為所需的ResponseModel
?
如何使用“ DataContractSerializer”並使用ReadObject方法? 它或多或少看起來像這樣:
var serializer = new DataContractSerializer(typeof(ResponseModel.Root));
var stream = await responseContent.ReadAsStreamAsync();
var response = serializer.ReadObject(stream) as ResponseModel;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.