Jquery calls the WCF sample code

Source: Internet
Author: User

No nonsense. Go straight to the topic.

WCF:

Restful has been popular in recent years. To make Ajax calls and support restful Uris, you must manually modify the SVC file and specify the factory after creating an Ajax-enabled WCF Service:

<% @ Servicehost Language = "C #" DEBUG = "true" service = "ajaxsample. helloworld" codebehind = "helloworld. SVC. cs"Factory = "system. servicemodel. Activation. webservicehostfactory"%>

NOTE: If no factory is added, WCF will not be able to directly access it in restful mode similar to http: // localhost/helloworld. svc/Hello/person/name.

Also remove the <enablewebscript/> in Web. config, which is similar:

<System. servicemodel>
<Behaviors>
<Endpointbehaviors>
<Behavior name = "ajaxsample. helloworldaspnetajaxbehavior">
<! -- <Enablewebscript/> -->
</Behavior>
</Endpointbehaviors>
</Behaviors>
<Servicehostingenvironment aspnetcompatibilityenabled = "true"
Multiplesitebindingsenabled = "true"/>
<Services>
<Service name = "ajaxsample. helloworld">
<Endpoint address = "" behaviorconfiguration = "ajaxsample. helloworldaspnetajaxbehavior"
Binding = "webhttpbinding" Contract = "ajaxsample. helloworld"/>
</Service>
</Services>
</System. servicemodel>

Now, start writing.CodeIn view of the two methods of get/post in a WCF call, We will write an example method for each of the following common cases:

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 helloworld {// <summary> // only restful methods that can be post are allowed /// </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> (); result. 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 <string> 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 = "*", uritemplate = "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 = "person"> </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); return 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:

<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/restfultest/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 "," welcome ": "DDD"} ', datatype: "html", success: function (data) {alert ("posttest call successful, return value:" + Data );}});}) </SCRIPT>

Sometimes, some sensitive information may be required as a parameter (such as the user name/user ID) in the method exposed by WCF. In this case, if you directly use js to call WCF, this part of information may be leaked on the client. In this scenario, we often use the server-side ashx for data transfer.

Testservice. SVC

 
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 = "userid"> </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. ashx

Using system. web; namespace ashx_jquery {// <summary> // summary description for ajaxprocess /// </Summary> public class ajaxprocess: ihttphandler {public void processrequest (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:

<% @ 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"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.