WCF web.config配置:
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="" closeTimeout="00:30:00" openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"> <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <!--below config is for https--> <!--<security mode="Transport"> <transport clientCredentialType="None" /> </security>--> </binding> </basicHttpBinding> </bindings> <services> <service name="WcfHost.Service2"> <endpoint address="Ajax" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="WcfHost.Service2" /> <endpoint address="Siverlight" binding="basicHttpBinding" contract="WcfHost.Service2" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="AjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
在JQuery使用:
<script type="text/javascript"> var Type; var Url; var Data; var ContentType; var DataType; var ProcessData; function WCFJSON() { Type = "POST"; Url = "/WcfHost/Service2.svc/Ajax/GetTest"; ContentType = "application/json; charset=utf-8"; DataType = "json"; ProcessData = true; CallService(); } function CallService() { $.ajax({ type: Type, //GET or POST or PUT or DELETE verb url: Url, data: Data, contentType: ContentType, dataType: DataType, processdata: ProcessData, success: function (msg) { ServiceSucceeded(msg); }, error: ServiceFailed }); } function ServiceFailed(xhr) { alert('Service call failed: ' + xhr.status + '' + xhr.statusText); Type = null; varUrl = null; Data = null; ContentType = null; DataType = null; ProcessData = null; } function ServiceSucceeded(result) { if (DataType == "json") { alert(result.d); } } $(document).ready( function () { WCFJSON(); } ); </script>
WCF文件
namespace WcfHost { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service2 { [OperationContract] public void DoWork() { // Add your operation implementation here return; } // Add more operations here and mark them with [OperationContract] [OperationContract] public string GetTest() { return "Test"; } } }