ASP.NET Web API Controller Specific Serializer

前端 未结 5 1953
深忆病人
深忆病人 2020-12-15 23:46

I\'ve a self host Web API with 2 controllers:

  • For controller 1, I need default DataContractSerializer (I\'m exposing EF 5 POCO)
  • For controller 2, I ne
5条回答
  •  死守一世寂寞
    2020-12-16 00:02

    You were very much on the right track. But you need to initallise a new instance of the XmlMediaTypeFormatter in your config attributes otherwise you will affect the global reference.

    As you know, you need to create 2 attributes based on the IControllerConfiguration interface.

    public class Controller1ConfigAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings controllerSettings,
                               HttpControllerDescriptor controllerDescriptor)
        {
            var xmlFormater = new XmlMediaTypeFormatter {UseXmlSerializer = true};
    
            controllerSettings.Formatters.Clear();
            controllerSettings.Formatters.Add(xmlFormater);
        }
    }
    
    public class Controller2ConfigAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings controllerSettings,
                               HttpControllerDescriptor controllerDescriptor)
        {
            var xmlFormater = new XmlMediaTypeFormatter();
            controllerSettings.Formatters.Clear();
            controllerSettings.Formatters.Add(xmlFormater);
        }
    }
    

    Then decorate your controllers with the relevant attribute

    [Controller1ConfigAttribute]
    public class Controller1Controller : ApiController
    {
    
    [Controller2ConfigAttribute]
    public class Controller2Controller : ApiController
    {
    

提交回复
热议问题