2012-03-06 66 views
2

我在ASP.NET MVC4 Web API中構建了一個API,並且其中一個操作返回了XML(當前以XElement的形式)。我無法控制這些數據,我只是把它傳遞出去。沒有可以將其反序列化的標準對象。ASP.NET MVC4 Web API MediaTypeFormatter將XElement轉換爲JSON的轉換器

public Task<XElement> Get(string queryName, string query)... 

我想要做的是使用MediaTypeFormatter將其轉換爲JSON,如果它被要求這樣。我已經開始寫MediaTypeFormatter和迷上它,但是當我打電話控制器上的「獲取」,它調用

protected override bool CanWriteType(Type type) 
{ 
    return true; 
} 
在MediaTypeFormatter

,但就從來沒有得到作爲OnWriteToStreamAsync方法。結果就是XML作爲一個字符串,例如

"<testXmlHere\/>" 

沒有人有任何想法如何解決這一問題呢?

感謝

+0

爲什麼您的API返回任務? – cecilphillip 2012-03-06 06:36:22

+0

它這樣做是爲了啓用異步執行。其上有很多文章,但幾乎整個堆棧都是爲異步執行而設計的。 – 2012-03-07 08:54:37

回答

2

您的自定義格式化程序可能插入格式化程序集合中JsonMediaTypeFormatter之後的格式化程序列表中。該格式化程序可以編寫XElement,它通過將XML表示形式編寫爲JSON字符串(無論這是一個好還是壞的想法是另一個討論)來實現。當添加格式化程序收集,使用Insert代替Add方法:

GlobalConfiguration.Configuration.Formatters.Insert(
    0, new MyCustomMediaTypeFormatter()); 
+0

謝謝......這麼簡單。 – 2012-03-07 07:46:36

0

這是一個瘋狂的建議...首先創建一個HttpResonponse消息和內容設置爲你檢索任何數據。嘗試創建一個自定義操作過濾器(System.Web.HttpFilters.ActionFilterAttribute)並實現OnActionExecuted方法。

在你的方法中,從HttpActionExecutedContext獲取相應的HttpRequest和HttpResponse對象。您可以從HttpRequest和HttpResponse中的數據中檢索Accept頭。根據需要根據請求的接受標頭格式化數據,並將其重新分配給響應內容。

你從哪裏來我?

0
public HttpResponseMessage<SensorUpdate> Post(int id) 
    { 
     SensorUpdate su = new SensorUpdate(); 
     su.Id = 12345;    
     su.Username = "SensorUpdateUsername"; 
     su.Text = "SensorUpdateText"; 
     su.Published = DateTime.Now; 


     HttpResponseMessage<SensorUpdate> response = new HttpResponseMessage<SensorUpdate>(su, 
        new MediaTypeHeaderValue("application/json")); 

     return response; 
    } 
+0

據透露 - 該HttpResponseMessage 對象已被棄用 – rboarman 2012-08-21 22:29:44

0

MVC4快速提示#3去除ASP.Net的Web API

全球

的XML格式化。 ASAX: 添加一行:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 

像這樣:

 protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 

     BundleTable.Bundles.RegisterTemplateBundles(); 
     GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
    }