asp.net web api 2.1在内容类型为application xml的控制器中获取null对象

时间:2014-09-10 04:12:55

标签: c# asp.net xml asp.net-web-api2

我有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);
    }

第三方组件向我发送内容类型为application / 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;

解决方案是什么?

2 个答案:

答案 0 :(得分:0)

public HttpResponseMessage Post([FromBody]string msg)
    {
XDocument xmlMessage =                 XDocument.Parse(msg);
        _logger.Log.Info("Got message: " + msg.ToString());
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

答案 1 :(得分:0)

有两个选项:

  1. 为参数object创建一个类,而不是匿名类型(object)。
  2. 或者如果您想要接收匿名实例,则应删除XML格式化程序,因为匿名类型are not supported by XML Formatter
  3.   

    XML序列化程序不支持匿名类型 JObject 实例。我

    因此,您的代码object msg对XML Serializer无效。