ASP.NET Web API Controller Specific Serializer

前端 未结 5 1909
深忆病人
深忆病人 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:04

    Mark Jones' answer has a big downside: By clearing all formatters it is not possible to request different ContentTypes and make use of the relevant formatter.

    A better way to enable the XMLSerializer per Controller is to replace the default formatter.

    public class UseXMLSerializerAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
        {
            // Find default XMLFormatter
            var xmlFormatter = controllerSettings.Formatters.FirstOrDefault(c => c.SupportedMediaTypes.Any(x => x.MediaType == "application/xml"));
    
            if (xmlFormatter != null)
            {
                // Remove default formatter
                controllerSettings.Formatters.Remove(xmlFormatter);
            }
    
            // Add new XMLFormatter which uses XmlSerializer
            controllerSettings.Formatters.Add(new XmlMediaTypeFormatter { UseXmlSerializer = true });
        }
    }
    

    And use it like this:

    [UseXMLSerializer]
    public TestController : ApiController
    {
        //Actions
    }
    

提交回复
热议问题