asp.net web api 2.1使用内容类型应用程序xml在控制器中获取null对象
本文关键字:xml 应用程序 控制器 对象 null 获取 类型 api web net asp | 更新日期: 2023-09-27 18:21:13
我有Api控制器,它只有POST和PUT
public HttpResponseMessage Post([FromBody]object msg)
{
_logger.Log.Info("Got message: " + msg.ToString());
return new HttpResponseMessage(HttpStatusCode.OK);
}
public HttpResponseMessage Put(object msg)
{
_logger.Log.Info("Got message: " + msg.ToString());
return new HttpResponseMessage(HttpStatusCode.OK);
}
第三方组件正在向我发送具有应用程序/xml 内容类型的请求
<EventList>
<Event>
<EventSubTypeId>65</EventSubTypeId>
<ExternalEventId>1</ExternalEventId>
<Direction>West</Direction>
<Road>I 70</Road>
<StartMileMarker>71.0</StartMileMarker>
<EndMileMarker>72.0</EndMileMarker>
<IsBothDirectionFlag>false</IsBothDirectionFlag>
<StartDate>2014-09-08T15:01:01.190-06:00</StartDate>
<Latitude>39.941208</Latitude>
<Longitude>-105.140121</Longitude>
<FatalityFlag>false</FatalityFlag>
<HazmatFlag>false</HazmatFlag>
<EstimatedTimeToClear>Test Estimated time to clear</EstimatedTimeToClear>
<GroupName>ITS</GroupName>
<Severity>Minimal</Severity>
<Classification>None</Classification>
<RoadwayClosure>No Lanes Closed</RoadwayClosure>
</Event>
然而,无论我如何尝试,我总是在msg对象中得到null我也试过
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
解决方案是什么?
public HttpResponseMessage Post([FromBody]string msg)
{
XDocument xmlMessage = XDocument.Parse(msg);
_logger.Log.Info("Got message: " + msg.ToString());
return new HttpResponseMessage(HttpStatusCode.OK);
}
有两个选项:
- 为参数
object
而不是匿名类型(object
)创建一个类 - 或者,如果要接收匿名实例,则应删除XML格式化程序,因为XML格式化程序不支持匿名类型:
XML序列化程序不支持匿名类型或JObject实例。I
因此,在您的代码中,object msg
对于XML序列化程序无效。