Custom Behavior won't register in my web.config

前端 未结 2 1076
终归单人心
终归单人心 2020-12-14 18:08

I have a working application using Json.NET (newtonsoft) as a custom serializer. Currently I\'m adding this derivative of WebHttpBehavior in a custom WebServiceHostFactory.

2条回答
  •  [愿得一人]
    2020-12-14 18:43

    The missing piece is the class BehaviorExtensionElement. In the OP I was attempting to add the WebHttpBehavior-derivative as an element. The BehaviorExtensionElement tells the config-parser which Type to use for a certain element.

    Here's the implementation I needed:

    public class NewtonsoftJsonBehaviorExtension : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get { return typeof(NewtonsoftJsonBehavior); }
        }
    
        protected override object CreateBehavior()
        {
            return new NewtonsoftJsonBehavior();
        }
    }
    

    This wasn't sufficient to get rid of my custom WebServiceHostFactory, of course. For I also had to add a custom ContentTypeMapper:

    public class NewtonsoftJsonContentTypeMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {
            return WebContentFormat.Raw;
        }
    }
    

    I could then use them in my Web.config. Here are the relevant parts of the working config. Firstly setting up the extension and configuring a behavior with it:

    
      
        
      
    
    
      
        
          
          
        
      
    
    

    Then configuring a webHttpBinding with my custom contentTypeMapper:

    
      
        
      
    
    

    Finally setting up an endpoint utilizing the above:

    
      
        
      
    
    

    Hope this stuff will help somebody out there. :)

提交回复
热议问题