简体   繁体   中英

asp.net web api 2.1 getting null object in controller with content type application xml

I have Api controller which has only POST and 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);
    }

3rd party component is sending me requests with content type of 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>

however no matter how I try I am always getting null in the msg object I have also tried

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
        xml.UseXmlSerializer = true;

what is the solution?

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

There are 2 options:

  1. Create a class for the parameter object instead of an anonymous type( object ).
  2. Or if you want to receive the anonymous instance, you should remove XML formatter, because anonymous types are not supported by XML Formatter :

The XML serializer does not support anonymous types or JObject instances. I

Therefore in your code object msg is not valid with XML Serializer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM