簡體   English   中英

asp.net Web API 2.1在控制器中使用內容類型應用程序xml獲取空對象

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

我有只有POST和PUT的Api控制器

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>

但是,無論我如何嘗試,我在味精對象中總是得到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);
    }

有2個選項:

  1. 為參數object而不是匿名type( object )創建一個類。
  2. 或者,如果您想接收匿名實例,則應刪除XML格式化程序,因為XML格式化程序不支持匿名類型:

XML序列化器不支持匿名類型JObject實例。 一世

因此,在您的代碼object msg對於XML序列化器無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM