How to produce XML output using WCF service?

前端 未结 2 2026
误落风尘
误落风尘 2021-01-03 05:13

I\'ve set up the following interface.

[ServiceContract]
public interface IService1
{
  [OperationContract]
  String Ping();
}

Its implement

2条回答
  •  别那么骄傲
    2021-01-03 05:53

    If you define your service endpoint as a WebHttp endpoint (a.k.a. REST endpoint), you'll get what you want. The easiest way to do that is to use the WebServiceHostFactory in your svc file:

    Service1.svc.

    <%@ ServiceHost Language="C#" Debug="true" Service="YourNamespace.Service1"
                    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
    

    Or you can define the endpoint without the factory, by defining that it will use the webHttpBinding and have a behavior:

    
      
        
          
            
          
        
      
      
        
          
        
      
    
    

    Update: Since some people were having issues, I wrote a full example of using XMLHttpRequest to talk to the service listed above. The code can be found at https://github.com/carlosfigueira/WCFQuickSamples/tree/master/WCFForums/QuickWebCode1 (look for StackOverflow_13345557), and it's mostly listed here.

    Service code (notice that I'm using JSON as the response, but XML works just as well):

    namespace StackOverflow_13345557
    {
        [ServiceContract]
        public interface IService1
        {
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            string Ping();
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            string PingWithParameters(int a, string b);
        }
    
        public class Service1 : IService1
        {
            public string Ping()
            {
                return "Hello";
            }
    
            public string PingWithParameters(int a, string b)
            {
                return string.Format("Hello {0} - {1}", a, b);
            }
        }
    }
    

    .SVC file - notice no usage of the Factory attribute, since I'm defining the endpoint via configuration:

    <%@ ServiceHost Language="C#" Debug="true" Service="StackOverflow_13345557.Service1"
                    CodeBehind="StackOverflow_13345557.svc.cs" %>
    

    web.config:

    
      
        
          
        
      
      
        
          
            
          
        
      
      
        
          
        
      
    
    

    HTML page accessing service (body only):

    
        
        

    One more update: added a self-contained, minimal project at https://skydrive.live.com/redir?resid=99984BBBEC66D789!6355 with the code listed above.

提交回复
热议问题