一步一步搭建客服系统 (4) 客户列表 - JS($.ajax)调用WCF 遇到的各种坑

阅读目录

本文以一个生成、获取“客户列表”的demo来介绍如何用js调用wcf,以及遇到的各种问题。

回到顶部

1 创建WCF服务

1.1 定义接口

创建一个接口,指定用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 接口实现

实现上面的接口,并加上AspNetCompatibilityRequirements 和 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 });
        }

        public List<string> GetAll()
        {
            return m_Queues.GetAllQueues().OrderBy(q => q.Value.CreateTime).Select(q => q.Key).ToList();
        }
    }
.
这里使用了一个静态的构造函数,这样它就只会被调用一次,以免每次调用时都会初始化队列。

1.3 定义服务

添加一个wcf service, 就一行:

<%@ ServiceHost Language="C#" Debug="true" Service="Youda.WebUI.Service.Impl.Queue" CodeBehind="~/Service.Impl/Queue.cs" %>

整体结构如下:

.

回到顶部

2 调用WCF

客户端调用Add方法,创建一组对话:

.

 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
            });

.
客服端取所有的客户:

.

$.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
            });

.

回到顶部

3 配置

webconfig配置如下:

.

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" />
    <bindings>
      <webHttpBinding>
        <binding name="HttpBind" openTimeout="00:10:00" sendTimeout="00:10:00"
          maxBufferSize="5242880" maxBufferPoolSize="5242880" maxReceivedMessageSize="5242880"
          crossDomainScriptAccessEnabled="true" />
        <binding name="HttpsBind" sendTimeout="00:10:00" maxBufferSize="5242880"
          maxReceivedMessageSize="5242880" crossDomainScriptAccessEnabled="true">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp helpEnabled="true" />
        </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" 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 遇到的各种坑

4.1 Status 为 200, status text为 ok, 但报错

http STATUS 是200,但是回调的却是error方法

查了下资料,应该是dataType的原因,dataType为json,但是返回的data不是json格式

于是将ajax方法里把参数dataType:"json"去掉就ok了

4.2 Json 数据请求报错(400 错误 )

详细的错误信息如下:

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 an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:content. The InnerException message was ‘There was an error deserializing the object of type System.String. Encountered invalid character…

解决方法是,要用JSON.stringify把data转一下,跟

data: ‘{"clientID":"‘ + clientID + ‘", "serviceID":"‘ + serviceID + ‘", "content":"‘ + content + ‘"}‘,

这样与拼是一样的效果,但明显简单多了

参考上面Add方法的调用。

4.3 参数没传进wcf方法里

调试进了这个方法,但参数全为空,发现用的是webget,改成post后就行了

[OperationContract]

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]

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

4.4 使用https时遇到了404 、 500的错误

先添加https的binding:

再设置下Service Behaviors:

详细的配置,可参考上面的完整文本配置

4.5 其它配置

时间设置长点, size设置大点:

<binding name="HttpBind" openTimeout="00:10:00" sendTimeout="00:10:00"
         maxBufferSize="5242880" maxBufferPoolSize="5242880" maxReceivedMessageSize="5242880"
         crossDomainScriptAccessEnabled="true" />

使用webHttpBinding 的binding;name和 contract 要写全:

<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" />

一步一步搭建客服系统

时间: 2024-12-07 13:27:46

一步一步搭建客服系统 (4) 客户列表 - JS($.ajax)调用WCF 遇到的各种坑的相关文章

一步一步搭建客服系统 (7) 多人共享的电子白板、画板

多人共享.同时操作的电子白板,让不同的参入者以不同的颜色来画画:可以保存当前room的内容,以让后来者可以直接加载所有内容. 在github上找到一个用html5 canvas实现的一个电子白板的例子: https://github.com/kblcuk/canvas-whiteboard 它是基于socket.io来实现多人白板的共享.操作.本文在它的基础上加上了房间,这样只有同一房间的人才会共享. 1  加入房间 客户端: var roomName = location.search.spl

一步一步搭建客服系统 (6) chrome桌面共享

本文介绍了如何在chrome下用webrtc来实现桌面共.因为必要要用https来访问才行,因此也顺带介绍了如何使用SSL证书. 1 chrome扩展程序 先下载扩展程序示例: https://github.com/otalk/getScreenMedia/tree/master/chrome-extension-sample 或 http://yunpan.cn/cHfwnrZcG2hsH  访问密码 1cf9 打开 manifest.json 文件,修改下面的内容: "content_scr

一步一步搭框架(asp.netmvc+easyui+sqlserver)-03

一步一步搭框架(asp.netmvc+easyui+sqlserver)-03 我们期望简洁的后台代码,如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using formula; using System.Data; namespace demo.Areas.basic.Controllers { public class

值得我们深入研究和学习:从零开始一步一步搭建坚不可摧的Web系统主流架构

本文标签: Web系统主流架构 搭建Web系统架构 缓存服务器 数据库架构   技术型初创公司  互联网杂谈 主题简介: 1.网站系统架构当前现状 2.Web系统主流架构解析 3.互联网技术团队初期组建经验分享 本文主要结合我之前在海尔电商平台和现在公司的一些实际架构经验,综合实际情况和个人的理解,跟大家分享一下搭建Web系统的一些常用的技术架构和应用技巧. 首先要跟大家探讨一个问题,就是当前传统IT企业或是传统企业的IT系统目前的系统架构是怎样的呢? 就我所经历的NEC软件.海尔集团.青岛航空

一步一步用jenkins,ansible,supervisor打造一个web构建发布系统

新blog地址:http://hengyunabc.github.io/deploy-system-build-with-jenkins-ansible-supervisor/ 一步一步用jenkins,ansible,supervisor打造一个web构建发布系统. 本来应该还有gitlab这一环节的,但是感觉加上,内容会增加很多.所以直接用github上的spring-mvc-showcase项目来做演示. https://github.com/spring-projects/spring-

一步一步教你在 Android 里创建自己的账号系统(一)

大家如果喜欢我的博客,请关注一下我的微博,请点击这里(http://weibo.com/kifile),谢谢 转载请标明出处(http://blog.csdn.net/kifile),再次感谢 大家在平时使用 Android 手机的时候,都会发现有些应用(例如 qq,微信,淘宝)为自己创建了账号系统,并且能够在设置页面看到他,可是当自己希望为自己的软件写一个账号系统的时候总是不知从何入手,现在我们就从头开始,一步一步打造属于自己应用的账号系统. 在进行设备账户管理的时候,我们会通过一个 Acco

一步一步学会系统发布

跟着牛腩老师做完发布系统,所有的结局都已写好,一场初雪,美的让我忘了还欠她一个美丽的转身--发布,但是小编呢,今天不以牛腩老师的新闻发布系统为例,以考试系统为例,跟小伙伴分享系统发布的点点滴滴.最近小编接手了一个高大上的任务,考试系统维护,用我小伙伴的话来吐槽一下就是:被考试系统折磨的不成人样了.维护工作是极大耐心的.从头到尾读着别人写的代码,复制别人的想法,做着自己的维护......是不是每个搞维护的都有要抽死coder的冲动"你丫写些什么,说好的注释代码2:1呢!" 说真心话,比珍

一步一步教你如何重装笔记本电脑系统?

本文标签:  电脑技巧 重装笔记本电脑系统 重装系统 重装dell联想宏碁电脑系统 原文地址:http://whosmall.com/?post=461 不知不觉中,已在程序猿这个职业中疯狂熬过去了3年时间,这3年虽然苹果技术天天更新,天天进步,但是如计算机常识方面却不忍心看它还是原地踏步! 从事编程时间久了,每次回家的时候,免不了会有朋友说起听说你从事计算机工作的吧,是啊,那帮我装个系统吧,最近电脑卡的要命.我家网线坏了,帮我连下网线吧!更有甚者,说我刚才误删某某重要文件,帮我恢复下吧! 你要

Linux入门之一步一步安装系统

1引言 2安装前的准备工作 下载vmware workstation 下载gentoo所需要的文件 知识点 1 我们下载的是基于x86架构的安装包在这里我们可以学习到用什么来区分架 构例如X86SPARC MIPS等这些标识主要是用来区分cpu的指令集的不同体系 不同型号的cpu有不同的指令集因此我们选择安装包时就需要选择和cpu指令匹配的包 2 几乎所有的个人电脑PC都是X86X86_64的 3 64位和32位的区别是cpu总线的宽度不同cpu总线又有数据总线控制总线和地址总线之分数据总线位数