jquery Invoke restful WCF sample code

Source: Internet
Author: User
Tags json

  This article mainly introduces the jquery call restful WCF Sample code (Get method/post method), the need for friends can come to the reference, hope to help everyone else

No nonsense, go straight to the theme   WCF end:   In recent years more popular restful, in order to enable Ajax calls, but also in order to support restful-style URI, after the creation of a ajax-enabled WCF service, You must manually modify the Svc file to specify factory, namely:   <%@ ServiceHost language= "C #" debug= "true" service= "Ajaxsample.helloworld" Codebehind= "HelloWorld.svc.cs" factory= "System.ServiceModel.Activation.WebServiceHostFactory"%>   Note: If you do not add factory, WCF will not be able to access it directly in a restful manner similar to http://localhost/helloWorld.svc/Hello/person/name.   also remove the <enablewebscript/> in web.config, which is similar to the following:   <system.serviceModel>     <behaviors >       <endpointBehaviors>         <behavior name= Ajaxsample.helloworldaspnetajaxbehavior ">           <!--<enablewebscript/>-- >         </behavior>       </endpointBehaviors>     </beha viors>     <servicehostingenvironment aspnetcompatibilityenabled= "true"       MultiplesitebindingseNabled= "true"/>     <services>       <service name= "Ajaxsample.helloworld" > & nbsp       <endpoint address= "" behaviorconfiguration= "Ajaxsample.helloworldaspnetajaxbehavior"   & nbsp       binding= "webhttpbinding" contract= "Ajaxsample.helloworld"/>       </service& Gt     </services>   </system.serviceModel>   OK, start writing code, given that WCF calls have get/post two ways, Here are a few common scenarios that write an example method: 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 helloworld      {          &NBSp <summary>         ///only post restful method          ///</summ ary>         ///<param name= "person" ></param>          <param name= "Welcome" ></param>         ///<returns></returns>& nbsp         [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);  &NBSp           result. ADD (Welcome);              return result;         }  &NB Sp        ///<summary>         ///only get RESTful method          ///</summary>         ///<param name= "Person" ></param>         ///<param name= "Welcome" ></param>         ///<retur ns></returns>          [operationcontract]          [ WebInvoke (method = "Get", UriTemplate = "Getrestfultest/{person}/{welcome}", Responseformat = Webmessageformat.json)]& nbsp         public list<string> getrestfultest (string person, string welcome)       &N Bsp   {              list<string> result = new List<strIng> ();                result. ADD ("Getrestfultest-> from server:");              result. ADD (person);              result. ADD (Welcome);              return result;         }  &NB Sp        ///<summary>         ///can get and post restful method     &N Bsp    ///</summary>         ///<param name= "Person" ></param>         ///<param name= "Welcome" ></param>         ///<retur ns></returns>          [operationcontract]          [ WebInvoke (method = "*", UriTemplate = "Restfultest/{person}/{welcome}", Responseformat = Webmessageformat.json)]          PublicList<string> restfultest (string person, string welcome)           {      &NBS P       list<string> result = new list<string> ();                result. ADD ("Restfultest-> from server:");              result. ADD (person);              result. ADD (Welcome);              return result;         }  &NB Sp           ///<summary>         ///only normal method of post (note: Post mode, Bo Dystyle must be set to wrappedrequest or wrapped)          ///</summary>        & nbsp <param name= "Person" ></param>         ///<param name= "Welcome" ></ param>         ///<returns></returns>         [operationcontract]          [WebInvoke (method = "POST", Responseform at = 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;         }  &NB Sp        ///<summary>         ///only get normal method       &NBSP ;  ///</summary>         ///<param name= "PersoN "></param>         ///<param name=" Welcome "></param>         ///<returns></returns>          [operationcontract]  & nbsp       [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;         }  &NB Sp                           } }   jquery call code: The code is as follows: <script type= "Text/javascript" >      $ () Ready (func tion () {              $.post ("helloworld.svc/postrestfultest/111/222", Function (data ) {              alert ("Postrestfultest call succeeded, return value is:" + data);         })             $.get ("helloworld.svc/getrestfultest/333/444", function (data) {               alert ("Getrestfultest call success, return value:" + data);        &NBS P }             $.get ("helloworld.svc/restfultest/555/666", function (data) {    &N Bsp         alert ("Restfultest get method call succeeded, return value is:" + data);         })               $.post ("helloworld.svc/restfultest/777/888", function (data) {      &NB Sp       ALert ("Restfultest Post method call succeeded, return value is:" + data);         })               $.get ("Helloworld.svc/gettest", {person: "AAA", Welcome: "BBB"}, function (data) {        &N Bsp     Alert ("Gettest call succeeded, return value:" + data);         });              $.ajax ({              URL: "Helloworld.svc/posttest",              type: "POST",              ContentType: "Application/json" ,              data: ' {person ': ' CCC ', ' Welcome ': ' DDD '} ',        &NB Sp     DataType: "html",              success:function (data) {alert ("Posttest Call succeeded, the return value is: "+ data"; }         } (;     })   </script>   Sometimes, WCF exposed methods may require some sensitive information to doFor parameters (such as user name/user ID, etc.), if the direct use of JS to invoke WCF, this part of the information may be leaked in the client, this scenario, we often use a service-side ashx to do the relay   TESTSERVICE.SVC   code as follows: Using system.servicemodel;    namespace ashx_jquery  {       [servicecontract]       public class Testservice       {           ///<summa ry>           ///get the payroll for the current user specified month            ///</summary& gt;           ///<param name= "userId" ></param>        &NBS P  ///<param name= "month" ></param>           ///<returns></ returns>           [OperationContract]          public double Ge tsalary (int userid,int month)           {              if (mont H = 1)//Only demo               {                  return 5000;        &NBS P    }              else              {&nbs P                 return 1000;             }&NBS P        }     } }   AJAXPROCESS.ASHX code is as follows: Using system.web;    N Amespace ashx_jquery  {     ///<summary>     ///Summary description for AJAXP rocess     ///</summary>      public class ajaxprocess:ihttphandler    & nbsp {            public void ProcessRequest (HttpContext context)         &NBS P {              context. Response.ContentType = "Text/plain";        &NBSP     String month = context. request["Month"];                Testservice WCF = new Testservice ();              Double salary = WCF. Getsalary (GetUserID (), Int. Parse (month));              context. Response.Write ("{Salary:" + Salary + "}");         }           &NB Sp  ///<summary>         ///get current user id         ///</summ ary>         ///<returns></returns>          Private in T GetUserID ()           {              return 1;         }            public bool isreusable          {               get     &NBSp       {                  return false;      &NB Sp      }         }     } }   jquery call: Code: <%@ Pag e 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 ">  <head runat=" Server ">      <title>jquery ashx sample</title>      <script type= "Text/javascript" src= "http://" Ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js "></script>      <script type=" text/ JavaScript ">          $ (). Ready (function () {              $ ("#btnTest"). Click (function () {  &nbsP               $.post (                  &NB Sp   "Ajaxprocess.ashx",                      {month:1},                      function (e) {          &NB Sp               var d = eval ("+ E +");            &NB Sp             alert (d.salary);                  & nbsp  }, "html");             })          })     &N Bsp </script>  </head>  <body>      <form id= "Form1" runat= "Server" >           <input type= "button" value= "Getsalary" id= "btntest"/>      </f orm>&nbsp </body>  </html>

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.