ASP.NET Web API sử dụng thương lượng nội dung để tự động deserialize một yêu cầu http đến vào một lớp mô hình. Trong hộp, điều này sẽ hoạt động với bất kỳ thông báo XML, JSON hoặc wwww-form-urlencoded nào.
public class ComputerController : ApiController
{
public void Post(ComputerInfo computer)
{
// use computer argument
}
}
Tạo một lớp mô hình mà bản đồ để các thuộc tính của XML.
public class ComputerInfo
{
public string Processor { get; set; }
public string HardDrive { get; set; }
}
XML đến này sẽ được deserialized để hydrate tham số máy tính trong phương pháp Post.
<ComputerInfo>
<Processor>AMD</Processor>
<HardDrive>Toshiba</HardDrive>
</ComputerInfo>
Nếu vì bất cứ lý do bạn muốn tự đọc và phân tích cú pháp xml đến, bạn có thể làm như vậy như thế này
string incomingText = this.Request.Content.ReadAsStringAsync().Result;
XElement incomingXml = XElement.Parse(incomingText);
Sử dụng ReadAsStreamAsync và Tải là một tùy chọn tốt hơn so với ReadAsString và Phân tích cú pháp. –
@DarrelMiller Tại sao vậy? – Despertar
Vì ReadAsString có thể chọn một mã hóa chuỗi khác với được định nghĩa trong tài liệu XML. –