Step by Step Build customer service System (4) Customer List-JS ($.ajax) call WCF encounters various pits

Source: Internet
Author: User

Read Catalogue

    • 1 Creating a WCF Service
    • 2 calling WCF
    • 3 Configuration
    • 4 Encounters with various pits

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

Back to top 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 class Queue:iqueue    {        static readonly objmanager<string, clientqueue> m_queues;        Static Queue ()        {            m_queues = new objmanager<string, clientqueue> ();        }        public void Add (string roomname)        {            m_queues.add (roomname, New Clientqueue () {createtime = DateTime.Now}); c12/>} public        list<string> GetAll ()        {            return m_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:


.

Back to top 2 call 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 ",                Processdata:true,                success: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 ",                Processdata:true,                success:function (result) {                    servicesucceeded ( result);                },                error:servicefailed            });

.

Back to Top 3 configuration

The Webconfig configuration is as follows:

.

<system.serviceModel> <servicehostingenvironment aspnetcompatibilityenabled= "true" Multiplesitebindingsenabled= "true" minfreememorypercentagetoactivateservice= "0"/> <bindings> <webhttp binding> <binding name= "Httpbind" opentimeout= "00:10:00" sendtimeout= "00:10:00" maxBufferSize= "52428        "Maxbufferpoolsize=" 5242880 "maxreceivedmessagesize=" 5242880 "crossdomainscriptaccessenabled=" true "/> <binding name= "Httpsbind" sendtimeout= "00:10:00" maxbuffersize= "5242880" maxreceivedmessagesize= "5242880" C Rossdomainscriptaccessenabled= "true" > <security mode= "Transport" > <transport clientcredent    Ialtype= "None"/> </security> </binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name= "Web" > <webhttp helpenabled= "t Rue "/> </behavior> </endpointbehaviors> <serviceBehaviors> <behavior name= "ServiceBehavior" > <servicemetadata        Httpgetenabled= "true" httpsgetenabled= "true"/> <servicedebug includeexceptiondetailinfaults= "true"/> </behavior> <behavior name= "Web" > <servicedebug includeexceptiondetailinfaults= "True "/> <servicemetadata httpgetenabled=" true "httpsgetenabled=" true "/> </behavior> < /servicebehaviors> </behaviors> <services> <service behaviorconfiguration= "ServiceBehavior" n Ame= "Youda.WebUI.Service.Impl.Queue" > <endpoint address= "" behaviorconfiguration= "web" binding= "Webhttpbindi        Ng "bindingconfiguration=" Httpbind "name=" Httpbind "contract=" Youda.WebUI.Service.Interface.IQueue "/> <endpoint behaviorconfiguration= "web" binding= "webhttpbinding" bindingconfiguration= "HttpsBind" Name= "httpsBin D "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 b ehaviorconfiguration= "web" binding= "webhttpbinding" bindingconfiguration= "Httpsbind" name= "HttpsBind" contract= "Y Ouda. WebUI.Service.Interface.IChat "/> </service> </services> </system.serviceModel>

.

Back to the top 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"/>

Build a customer service system step by step

Step by Step Build customer service System (4) Customer List-JS ($.ajax) call WCF encounters various pits

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.