我有一个自己的主机Web API与2个控制器:
>对于控制器1,我需要默认的DataContractSerializer(我正在暴露EF 5 POCO)
>对于控制器2,我需要使用参数UseXmlSerializer设置为true(我暴露一个XmlDocument)的XmlFormatter,
我在控制器初始化期间尝试设置格式化程序,但配置似乎是全局的,影响所有控制器:
public class CustomConfigAttribute : Attribute,IControllerConfiguration { public void Initialize(HttpControllerSettings settings,HttpControllerDescriptor descriptor) { settings.Formatters.XmlFormatter.UseXmlSerializer = true; } }
我该如何解决?
解决方法
你非常在正确的轨道上.但是您需要在配置属性中启动XmlMediaTypeFormatter的新实例,否则您将影响全局引用.
您知道,您需要根据IControllerConfiguration接口创建2个属性.
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,HttpControllerDescriptor controllerDescriptor) { var xmlFormater = new XmlMediaTypeFormatter(); controllerSettings.Formatters.Clear(); controllerSettings.Formatters.Add(xmlFormater); } }
然后用相关属性装饰你的控制器
[Controller1ConfigAttribute] public class Controller1Controller : ApiController { [Controller2ConfigAttribute] public class Controller2Controller : ApiController {