JS ($.ajax) calls the various pits that WCF encounters

Source: Internet
Author: User

This article describes how to invoke WCF with JS and the various problems encountered with a demo that generates and gets the customer list.

1 Create a WCF Service 1.1 definition interface to create an interface that specifies the format in JSON:

[ServiceContract]    Interface Iqueue    {        [OperationContract]        [WebInvoke (Method = "POST", bodystyle = webmessagebodystyle.wrapped, Requestformat = Webmessageformat.json, Responseformat = WebMessageFormat.Json)]        void ADD (string roomname);        [OperationContract]        [WebGet (Responseformat=webmessageformat.json)]        List<string> GetAll ();    }
.1.2 Interface Implementation

Implement the above interface, plus aspnetcompatibilityrequirements and Javascriptcallbackbehavior:

.
[Aspnetcompatibilityrequirements (Requirementsmode = aspnetcompatibilityrequirementsmode.allowed)] [Javascriptcallbackbehavior (Urlparametername = "Callback")] Public classQueue:iqueue {StaticReadOnly objmanager<string, clientqueue> m_queues;StaticQueue () {m_queues =NewObjmanager<string, clientqueue> (); } Public voidADD (String roomname) {M_queues.add (Roomname,NewClientqueue () {createtime = DateTime.Now}); } PublicList<string> GetAll () {returnM_queues.getallqueues (). (q = q.value.createtime). Select (q = q.key).        ToList (); }    }

.
A static constructor is used here so that it is only called once, so that the queue is initialized each time it is called.

1.3 Defining services

Add a WCF service, on one line:

<%@ ServiceHost language= "C #" debug= "true" service= "Youda.WebUI.Service.Impl.Queue" codebehind= "~/service.impl/queue.cs"%>

The overall structure is as follows:


.

2 calling WCF

The client calls the Add method to create a set of dialogs:

.

var data = {' Roomname ': ClientID};            $.ajax ({                type: "POST",                URL: "service/queue.svc/add",                data:JSON.stringify (data),                  contentType: "Application/json; Charset=utf-8",                dataType:"json",                true,                function (msg) {                    servicesucceeded (msg);                },                error:servicefailed            });

.
Customer service end to all customers:

.

$.ajax ({                type: "GET",                URL: "service/queue.svc/getall",                contentType: "  Application/json; Charset=utf-8",                dataType:"json",                true,                function (result) {                    servicesucceeded (result);                },                error:servicefailed            });
.

3 Configuration

The Webconfig configuration is as follows:

.

<system.serviceModel> <servicehostingenvironment aspnetcompatibilityenabled= "true"Multiplesitebindingsenabled="true"Minfreememorypercentagetoactivateservice="0"/> <bindings> <webHttpBinding> <bindingname="Httpbind"Opentimeout="00:10:00"Sendtimeout="00:10:00"Maxbuffersize="5242880"Maxbufferpoolsize="5242880"Maxreceivedmessagesize="5242880"Crossdomainscriptaccessenabled="true"/> <bindingname="Httpsbind"Sendtimeout="00:10:00"Maxbuffersize="5242880"Maxreceivedmessagesize="5242880"Crossdomainscriptaccessenabled="true"> <security mode="Transport"> <transport clientcredentialtype="None"/> </security> </binding> </webHttpBinding> </bindings> <behavi Ors> <endpointBehaviors> <behaviorname="Web"> <webhttp helpenabled="true"/> </behavior> </endpointBehaviors> <serviceBehaviors> <behaviorname="ServiceBehavior"> <servicemetadata httpgetenabled="true"Httpsgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="true"/> </behavior> <behaviorname="Web"> <servicedebug includeexceptiondetailinfaults="true"/> <servicemetadata httpgetenabled="true"Httpsgetenabled="true"/> </behavior> </serviceBehaviors> </behaviors> <services> <service Behaviorconfiguration= "ServiceBehavior"name="Youda.WebUI.Service.Impl.Queue"> <endpoint address=""Behaviorconfiguration="Web"Binding="webhttpbinding"Bindingconfiguration="Httpbind"name="Httpbind"Contract="Youda.WebUI.Service.Interface.IQueue"/> <endpoint behaviorconfiguration="Web"Binding="webhttpbinding"Bindingconfiguration="Httpsbind"name="Httpsbind"Contract="Youda.WebUI.Service.Interface.IQueue"/> </service> <service behaviorconfiguration="ServiceBehavior"name="Youda.WebUI.Service.Impl.Chat"> <endpoint address=""Behaviorconfiguration="Web"Binding="webhttpbinding"Bindingconfiguration="Httpbind"name="Httpbind"Contract="Youda.WebUI.Service.Interface.IChat"/> <endpoint behaviorconfiguration="Web"Binding="webhttpbinding"Bindingconfiguration="Httpsbind"name="Httpsbind"Contract="Youda.WebUI.Service.Interface.IChat"/> </service> </services> </system.serviceModel>
.

4 encountered a variety of pits 4.1 status, status text is OK, but error

The HTTP STATUS is 200, but the callback is the error method

Check the information, it should be datatype reason, datatype is JSON, but the returned data is not in JSON format

The Ajax method is then datatype the parameter: "JSON" to get rid of the OK

4.2 Json Data Request error (400 errors)

Detailed error information is as follows:

Service call failed:

status:400; Status Text:bad Request; Response text: <?xml version= "1.0" encoding= "Utf-8"?>

The server encountered an error processing the request. The exception message is ' The formatter threw a exception while trying to deserialize the Message:there were an error WHI Le trying to deserialize parameter http://tempuri.org/:content. The innerexception message was ' There is an error deserializing the object of type System.String. Encountered invalid character ...

The solution is to use json.stringify to turn the data

Data: ' {' ClientID ': ' + ClientID + ', ' ServiceID ': ' + ServiceID + ', ' content ': ' + content + ' '} ',

This is the same effect as the spelling, but it's obviously much simpler.

Refer to the call of the Add method above.

4.3 parameter not passed into WCF method

Debugging into this method, but the parameters are all empty, found that the use of webget, changed to post on the line

[OperationContract]

[WebInvoke (Method = "POST", Requestformat = Webmessageformat.json, bodystyle = webmessagebodystyle.wrapped, Responseformat = Webmessageformat.json)]

List<string> getmsg (string clientID, int count);

4.4 404, 500 error encountered while using HTTPS

Add the binding for HTTPS first:

Then set the service behaviors:

Detailed configuration, refer to the full text configuration above

4.5 Other configurations

Time set Long point, size set large point:

<binding name= "Httpbind" opentimeout= "00:10:00" sendtimeout= "00:10:00"
Maxbuffersize= "5242880" maxbufferpoolsize= "5242880" maxreceivedmessagesize= "5242880"
Crossdomainscriptaccessenabled= "true"/>

Use WebHttpBinding's binding;name and contract to write full:

<service behaviorconfiguration= "ServiceBehavior" name= "Youda.WebUI.Service.Impl.Queue" >
<endpoint address= "" behaviorconfiguration= "web" binding= "webhttpbinding"
bindingconfiguration= "Httpbind" name= "Httpbind" contract= "Youda.WebUI.Service.Interface.IQueue"/>

The customer service system.

JS ($.ajax) calls the various pits that WCF encounters

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.