2016-06-27 12 views
0

在ASP.NET Web API中,我需要強制XML輸出用於單個方法,但保留爲其他用戶啓用JSON格式化程序。我看到的題目一切都建議從GlobalConfiguration取出JSON格式如下:在ASP.NET Web API中選擇性地禁用XML格式化程序

// remove JSON formatter 
var formatters = GlobalConfiguration.Configuration.Formatters; 
formatters.Remove(formatters.JsonFormatter); 

這工作,但廣泛禁止JSON輸出應用。我需要能夠指定特定方法或控制器的格式化程序而不影響全局配置。這是可能的還是隻能通過GlobalConfiguration完成?

回答

1

微軟爲此特定目的推出了per-controller configuration。你需要將你的功能分解爲不同的控制器,但希望這對你的特定目標來說不會太麻煩(甚至可能是一種改進)。

基本上,這裏是你怎麼做:

  1. 設置基本JSON格式對於一般情況
  2. 介紹了XML方法特定的控制器,並給它一個特定的配置:

[XMLControllerConfig] 
public class XMLController: ApiController 
{ 
    [HttpGet] 
    public string SomeMethod(string someArgument) 
    { 
     return "abc"; 
    } 
} 

...

class XMLControllerConfigAttribute: Attribute, IControllerConfiguration 
{ 
    public void Initialize(HttpControllerSettings controllerSettings, 
          HttpControllerDescriptor controllerDescriptor) 
    { 
     controllerSettings.Formatters.Clear(); 
     controllerSettings.Formatters.Add(new XMLFormatter()); 
    } 
} 
+0

這工作完美,除了我需要使用System.Net.Http.Formatting.XmlMediaTypeFormatter而不是XMLFormatter。 – rybl

相關問題