Can a WCF OperationContract method's WebGet attribute have multiple ResponseFormat types?

前端 未结 2 1177
醉酒成梦
醉酒成梦 2021-02-01 21:50

I have a ServiceContract describing a method used in a WCF service. The method has a WebGet attribute which defines a UriTemplate and ResponseFormat.

I want to reuse a

2条回答
  •  囚心锁ツ
    2021-02-01 22:23

    If I remember correctly, below method worked for me:

    Contract for json service:

    [ServiceContract]
    public interface IServiceJson {
      [OperationContract()]
      [WebGet(UriTemplate = "Operation/?param={param}",
                             ResponseFormat = WebMessageFormat.Json)]
      ReturnType Operation(string param);
    }
    

    Contact for xml service:

    [ServiceContract]
    public interface IServiceXml {
      [OperationContract(Name = "OperationX")]
      [WebGet(UriTemplate = "Operation/?param={param}",
                             ResponseFormat = WebMessageFormat.Xml)]
      ReturnType Operation(string param);
    }
    

    Implementation for both:

    public class ServiceImplementation : IServiceJson, IServiceXml {
      ReturnType Operation(string param) {
        // Implementation
      }
    }
    

    And web.config configuration (note endpoints for json and xml responses):

      
        
          
            
              
            
          
          
            
              
              
            
          
        
        
          
            
              
                
              
            
            
              
                
              
            
            
          
        
        
          
            
              
            
          
        
      
    

    Now you can call your service like this: json response: http://yourServer/json/Operation/?param=value xml response: http://yourServer/xml/Operation/?param=value

    (Sorry if there are any bugs in code above, I didn't run it for verification).

提交回复
热议问题