This article mainly introduces jQuery calling RESTful WCF sample code (GET method/POST method). If you need it, you can refer to it and hope to help you.
No nonsense. Let's go straight to the topic: restful has been popular in recent years. To make ajax calls and support restful Uris, after creating an Ajax-enabled wcf Service, you must manually modify the svc file and specify the Factory, that is, <% @ ServiceHost Language = "C #" Debug = "true" Service = "ajaxSample. helloWorld "CodeBehind =" HelloWorld. svc. cs "Factory =" System. serviceModel. activation. webServiceHostFactory "%> Note: If no Factory is added, wcf cannot use a format similar to http: // localhost/helloWorld. svc/Hello/person/name for direct access in restful mode. Also, remove <enableWebScript/> in web. config, which is similar to <system. serviceModel> <behaviors> <endpointBehaviors> <behavior name = "ajaxSample. HelloWorldAspNetAjaxBehavior"> <! -- <EnableWebScript/> --> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment identifier = "true" multipleSiteBindingsEnabled = "true"/> <services> <service name = "ajaxSample. helloWorld "> <endpoint address =" "behaviorConfiguration =" ajaxSample. helloWorldAspNetAjaxBehavior "binding =" webHttpBinding "contract =" ajaxSample. helloWorld "/> </service> </services> </system. ser ViceModel> Well, start to write code. In view of the two methods of GET/POST in the wcf call, We will write an example Method for several common cases: the code is as follows: using System. collections. generic; using System. serviceModel; using System. serviceModel. activation; using System. serviceModel. web; namespace ajaxSample {[ServiceContract (Namespace = "http://yjmyzz.cnblogs.com/")] [AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. allowed)] public class HelloWorl D {// <summary> /// only Restful methods that can be Post // </summary> /// <param name = "person"> </param> // /<param name = "welcome"> </param> // <returns> </returns> [OperationContract] [WebInvoke (Method = "POST ", uriTemplate = "PostRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat. json)] public List <string> PostRestfulTest (string person, string welcome) {List <string> result = new List <string> (); re Sult. add ("PostRestfulTest-> from server:"); result. add (person); result. add (welcome); return result ;} /// <summary> /// only Get Restful Methods // </summary> /// <param name = "person"> </param> // <param name = "welcome"> </param> // <returns> </returns> [OperationContract] [WebInvoke (Method = "GET ", uriTemplate = "GETRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat. json)] public List <stri Ng> GETRestfulTest (string person, string welcome) {List <string> result = new List <string> (); result. add ("GETRestfulTest-> from server:"); result. add (person); result. add (welcome); return result ;} /// <summary> /// you can Get and Post the Restful method // </summary> /// <param name = "person"> </param> // /<param name = "welcome"> </param> // <returns> </returns> [OperationContract] [WebInvoke (Method = "*", uriTemplat E = "RestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat. json)] public List <string> RestfulTest (string person, string welcome) {List <string> result = new List <string> (); result. add ("RestfulTest-> from server:"); result. add (person); result. add (welcome); return result ;}/// <summary> // a common method that can only be Post (Note: In Post mode, BodyStyle must be set to WrappedRequest or Wrapped) /// </summary> /// <param name = "pers On "> </param> /// <param name =" welcome "> </param> // <returns> </returns> [OperationContract] [WebInvoke (Method = "POST ", responseFormat = WebMessageFormat. json, BodyStyle = WebMessageBodyStyle. wrappedRequest)] public List <string> PostTest (string person, string welcome) {List <string> result = new List <string> (); result. add ("PostRestfulTest-> from server:"); result. add (person); result. add (welcome); r Eturn result ;} /// <summary> /// common methods that can only be Get /// </summary> /// <param name = "person"> </param> // <param name = "welcome"> </param> // <returns> </returns> [OperationContract] [WebInvoke (Method = "GET ", responseFormat = WebMessageFormat. json)] public List <string> GETTest (string person, string welcome) {List <string> result = new List <string> (); result. add ("GETTest-> from server:"); result. add (person ); Result. add (welcome); return result ;}} jQuery call code: the code is as follows: <script type = "text/javascript" >$ (). ready (function () {$. post ("HelloWorld. svc/PostRestfulTest/111/222 ", function (data) {alert (" PostRestfulTest called successfully, returned value: "+ data) ;}) $. get ("HelloWorld. svc/GETRestfulTest/333/444 ", function (data) {alert (" GETRestfulTest call successful, return value: "+ data) ;}) $. get ("HelloWorld. svc/rest fultest/555/666 ", function (data) {Alert ("RestfulTest GET method call successful, return value:" + data) ;}) $. post ("HelloWorld. svc/RestfulTest/777/888 ", function (data) {alert (" RestfulTest POST method call successful, return value: "+ data) ;}) $. get ("HelloWorld. svc/GETTest ", {person:" aaa ", welcome:" bbb "}, function (data) {alert (" GETTest call successful, return value: "+ data) ;}); $. ajax ({url: "HelloWorld. svc/PostTest ", type:" POST ", contentType:" application/json ", data: '{" person ":" ccc "," w Elcome ":" ddd "} ', dataType:" html ", success: function (data) {alert (" PostTest call successful, return value: "+ data) ;}}) ;}) </script> sometimes, some sensitive information may be required as parameters (such as user name/user ID) in the methods exposed by WCF ), in this case, if you directly use js to call wcf, this part of information may be leaked to the client. In this scenario, we often use the server-side ashx for transit TestService. the svc code is as follows: using System. serviceModel; namespace ashx_jQuery {[ServiceContract] public class TestService {// <summary> // obtain the salary of the current user for the specified month /// </summary> /// <param name = "u SerId "> </param> /// <param name =" month "> </param> // <returns> </returns> [OperationContract] public double GetSalary (int userId, int month) {if (month = 1) // just for demonstration. {return 5000;} else {return 1000 ;}}} AjaxProcess. the ashx code is as follows: using System. web; namespace ashx_jQuery {// <summary> // Summary description for AjaxProcess /// </summary> public class AjaxProcess: IHttpHandler {public void Proc EssRequest (HttpContext context) {context. response. contentType = "text/plain"; string month = context. request ["month"]; TestService wcf = new TestService (); double salary = wcf. getSalary (GetUserId (), int. parse (month); context. response. write ("{salary:" + salary + "}");} /// <summary> /// obtain the current user ID /// </summary> /// <returns> </returns> private int GetUserId () {return 1 ;} public bool IsReusable {Get {return false ;}}} jQuery call: the code is as follows: <% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "default. aspx. cs "Inherits =" ashx_jQuery. _ default "%> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">