如果我没记错的话,下面的方法对我有效:
JSON服务合同:
[ServiceContract]
public interface IServiceJson {
[OperationContract()]
[WebGet(UriTemplate = "Operation/?param={param}",
ResponseFormat = WebMessageFormat.Json)]
ReturnType Operation(string param);
}
XML服务联系人:
[ServiceContract]
public interface IServiceXml {
[OperationContract(Name = "OperationX")]
[WebGet(UriTemplate = "Operation/?param={param}",
ResponseFormat = WebMessageFormat.Xml)]
ReturnType Operation(string param);
}
两者的实施:
public class ServiceImplementation : IServiceJson, IServiceXml {
ReturnType Operation(string param) {
// Implementation
}
}
和web.config配置(注意json和xml响应的端点):
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="serviceBehaviour" name="ServiceImplementation">
<endpoint address="json/" behaviorConfiguration="webHttp" binding="webHttpBinding"
bindingConfiguration="webHttpBindingSettings" contract="IServiceJson">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="xml/" behaviorConfiguration="webHttp" binding="webHttpBinding"
bindingConfiguration="webHttpBindingSettings" contract="IServiceXml">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingSettings">
<readerQuotas maxStringContentLength="5000000"/>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
现在您可以这样呼叫您的服务:
JSON响应:
http://yourServer/json/Operation/?param=value
XML响应:
http://yourServer/xml/Operation/?param=value
(抱歉,如果上面的代码中有任何错误,我没有运行它进行验证)。