在web api中使用xml序列化时,property为null

时间:2013-11-21 01:57:37

标签: asp.net asp.net-web-api

我正在尝试发送以下xml

<dataset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.uisol.com/model">
<extAlert SendFrom="SendFrom" Target="Target" OID="0" UrgentFlag="0" />
</dataset>

作为webapi请求的帖子

 HttpResponseMessage Post([FromBody]SendNotificationRequest dataset)

使用以下定义的类

 [XmlRoot(Namespace = "http://www.uisol.com/model",
     ElementName = "dataset",
     DataType = "string",
     IsNullable = true)]
    public class SendNotificationRequest
    {
        [XmlElement(
         ElementName = "extAlert",
         Namespace = "http://www.uisol.com/model")]
        public DRMSAlertRequest ExtAlert { get; set; }
    }
}

公共类DRMSAlertRequest:IDRMSAlert {

[XmlAttribute]
public string SendFrom { get; set; }
[XmlAttribute]
public string Target { get; set; }
[XmlAttribute]
public string SendTo { get; set; }
[XmlAttribute]
public string BlindTo { get; set; }
[XmlAttribute]
public string ReplyTo { get; set; }
[XmlAttribute]
public string FailureTo { get; set; }
[XmlAttribute]
public int OID { get; set; }
[XmlAttribute]
public string Subject { get; set; }
[XmlAttribute]
public string Message { get; set; }
[XmlAttribute]
public char UrgentFlag { get; set; }

}

我还制作了xmlmedia格式化程序,如下所示

 var formatter = new XmlMediaTypeFormatter {UseXmlSerializer = true};
            config.Formatters.Add(formatter);

            var xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
            xmlFormatter.UseXmlSerializer = true;
            xmlFormatter.SetSerializer<SendNotificationRequest>(new XmlSerializer(typeof(SendNotificationRequest)));
            xmlFormatter.SetSerializer<DRMSAlertRequest>(new XmlSerializer(typeof(DRMSAlertRequest)));
        }

我在webapi控制器上收到ExtAlert为null。可能是什么原因?

1 个答案:

答案 0 :(得分:0)

 httpRequest.ContentType = "application/x-www-form-urlencoded";

将此更改为

httpRequest.ContentType =“application / xml”;