Welcome to the Csdn-markdown Editor

Source: Internet
Author: User

These days in learning restful WCF feel more comfortable to call, just can't generate classes directly in VS ...
The first is the construction of restful WCF

First, the interface file:

[Servicecontract]public interface itestwcf{[OperationContract] [WebGet (Responseformat = Webmessageformat. Json, UriTemplate ="DoWork")] BOOL DoWork ();[OperationContract] [WebInvoke (Responseformat = Webmessageformat. Json, bodystyle = Webmessagebodystyle. Wrapped, UriTemplate ="Webinvokewithnoargs", Method ="POST")] Returnobj Webinvokewithnoargs ();[OperationContract] [WebInvoke (Responseformat = Webmessageformat. Json, Requestformat =webmessageformat. Json, Bodystyle =webmessagebodystyle. Wrappedrequest, UriTemplate ="Webinvokewithargs", Method ="POST")] Returnobj Webinvokewithargs (String str);[OperationContract] [WebGet (Responseformat = Webmessageformat. Json, Requestformat = Webmessageformat. Json, UriTemplate ="Webgetwithnoargs")] Returnobj Webgetwithnoargs ();[OperationContract] [WebGet (Responseformat = Webmessageformat. Json, Requestformat = Webmessageformat. Json, UriTemplate ="Webgetwithargs/{str}")] Returnobj Webgetwithargs (String str);}

Then the implementation file

[Aspnetcompatibilityrequirements (Requirementsmode = aspnetcompatibilityrequirementsmode.allowed)] Public classtestwcf:itestwcf{ Public BOOL DoWork()    {return true; } PublicReturnobjWebgetwithargs(stringSTR) {return NewReturnobj (str); } PublicReturnobjWebgetwithnoargs()    {return NewReturnobj ("Get success!"); } PublicReturnobjWebinvokewithargs(stringSTR) {return NewReturnobj (str); } PublicReturnobjWebinvokewithnoargs()    {return NewReturnobj ("Invoke success!"); }}

Explain
The difference between WebInvoke and WebGet can be understood as a post and a get. But WebInvoke's method can also be get,webget only get
Responseformat = Webmessageformat.json This is the way to use Json when response
UriTemplate This can understand an address such as UriTemplate = "Webinvokewithnoargs" You can use Http://xxx.xxx.xxx/xxx.svc/WebInvokeWithNoArgs To access them.
When method is get, and there are parameters, you can pass parameters to WCF using UriTemplate = "method address/{parameter}/{}". Of course, the post still writes the JSON to be honest ~
Bodystyle =webmessagebodystyle.wrappedrequest this for packaging request, this author also did not understand the specific function, just do not have this sentence when the Ajax return status of 200 plus just fine ...
Bodystyle = Webmessagebodystyle.wrappedresponse This is for packaging response, that is, when Ajax gets JSON, there will be {"Webinvokewithnoargsresult": {" Str ":" Invoke success! "}} (with) {"str": "Invoke success!"} No
Webmessagebodystyle and two are bare and wrapped. Bare is completely non-packaged, and the wrapped is packaged in two of them.

Then the class that is transferred:

[DataContract]publicclass ReturnObj{    0)]    publicstring str;    publicReturnObj(string args)    {        str = args;    }}

If you want to add a field to the JSON, use DataMember to mark it. If this field is not visible in Datamember,json! and whether it is visible is not related to private public.
Order is the sequence of fields when converted to JSON. When there is an order, the small one is in front.

    0)]    privatestring str;    1)]    publicint num;    2)]    publicbool ok;

The result is {"str": "Invoke success!", "num": 1, "OK": true}
Then seemingly without order in the front of the add order (this is not sure, did a few experiments seems to be the case)

If the basic type (such as bool or something) is a simple value, there is no JSON format

Then the configuration file

 <system.servicemodel>    <behaviors>      <endpointbehaviors>        <behavior name="Testwcfbehavior"></behavior>      </endpointbehaviors>      <servicebehaviors>        <behavior name="">          <servicemetadata httpgetenabled="true" httpsgetenabled=  "True" />          <servicedebug includeexceptiondetailinfaults="false" />        </behavior>      </servicebehaviors>    </Behaviors>    <servicehostingenvironment aspnetcompatibilityenabled="true"  multiplesitebindingsenabled="true" />            <services>      <service name="TESTWCF">        <endpoint address= "" behaviorconfiguration= "testwcfbehavior" Binding="webhttpbinding" contract="ITESTWCF"></Endpoint>      </Service>    </Services>  </system.servicemodel>

Configuration file must be careful to check that there is no leakage, because the configuration file is wrong is not directly linked to the service is not access to ...

Then how to invoke WCF with Ajax ...
If you use jquery, it's $.ajax ().
POST:

$.ajax ({URL:".. /testwcf.svc/webinvokewithargs ", type:"POST", ContentType:"Text/json", Asnyc:"false", Data:' {' str ': ' Invoke Test '} ', DataType:' JSON ', Success: function (resultobj) {                varResultStr =String(JSON. Stringify (Resultobj));            alert (RESULTSTR); }, Error: function (XMLHttpRequest, Textstatus, Errorthrown) {alert (xmlhttprequest.status);                alert (xmlhttprequest.readystate);            alert (textstatus); }        });

GET

 $.ajax ({URL:  "Testwcf.svc/webgetwithargs/get Test" , type:  "Get" , Asnyc: false , DataType:  ' JSON ' , success: function   (resultobj)  { var  resultstr = string  (json . Stringify (resultobj)); alert (RESULTSTR); }, Error: function   (XML HttpRequest, Textstatus, Errorthrown)  { alert (xmlhttprequest.status); alert (xmlhttprequest.readystate); alert (textstatus); } }); 

Note The URL of these three letters cannot be capitalized-_-| |

If you write Ajax,

<script type="Text/javascript">    varXmlHttp;///The following function generates different Ajax objects depending on whether IE is a browser.     function createxmlhttprequest() {        if(Window. ActiveXObject) {xmlHttp =NewActiveXObject ("Microsoft.XMLHTTP"); }Else if(Window. XMLHttpRequest) {xmlHttp =NewXMLHttpRequest (); }    }//post     function doPost() {        varURL ="Testwcf.svc/webinvokewithargs";vardata =' {' str ': ' Invoke Test '} ';//Note for JSON formatCreatexmlhttprequest (); Xmlhttp.open ("POST"Urlfalse);//open (method, address, sync)Xmlhttp.setrequestheader ("Content-type","Text/json"); Xmlhttp.onreadystatechange = function () {           if(Xmlhttp.readystate = =4) && (Xmlhttp.status = = $) {alert (xmlhttp.responsetext); }Else{alert (xmlhttp.status); }} xmlhttp.send (data);return false; }//get     function doget() {        varURL ="Testwcf.svc/webgetwithnoargs";        Createxmlhttprequest (); Xmlhttp.onreadystatechange = function () {            if(Xmlhttp.readystate = =4) && (Xmlhttp.status = = $) {alert (xmlhttp.responsetext); }Else{alert (xmlhttp.status); }} xmlhttp.open ("GET"Urlfalse); Xmlhttp.send ("");return false; }</script>

Notice that you set onReadyStateChange's handler function and send again.

As for the C # client side, it can be handled with Webhttprequest and Webhttpresponse.
GET

        static void Main(string[] args)        {            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:65143/testwcf.svc/WebGetWithNoArgs");            req.Method"GET";            HttpWebResponse res = (HttpWebResponse)req.GetResponse();            StreamReader sr = new StreamReader(res.GetResponseStream());            Console.WriteLine(sr.ReadToEnd());        }

POST

static void Main (string[] args) {HttpWebRequest req = (HttpWebRequest) WebRequest. Create("Http://localhost:65143/testwcf.svc/WebInvokeWithArgs");Req. Method="POST";Req. ContentType="Application/json";String data = @"{""STR"":""from C #""}";byte[] SendData = Encoding. Default. GetBytes(data);Req. ContentLength= SendData. Length;Req. GetRequestStream(). Write(SendData,0, SendData. Length);Req. GetRequestStream(). Close();HttpWebResponse res = (HttpWebResponse) req. GetResponse();StreamReader sr = new StreamReader (res. GetResponseStream());Console. WriteLine(SR. ReadToEnd());}

Welcome to the Csdn-markdown Editor

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.