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

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

 

1 创建WCF服务

1.1 定义接口

创建一个接口,指定用json的格式:
 
 
.

1.2 接口实现

实现上面的接口,并加上AspNetCompatibilityRequirements 和 JavascriptCallbackBehavior :

.

.
这里使用了一个静态的构造函数,这样它就只会被调用一次,以免每次调用时都会初始化队列。

 

1.3 定义服务

添加一个wcf service, 就一行:

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

 

整体结构如下:

image


.

2 调用WCF

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

.

.
客服端取所有的客户:

.

.

 

3 配置

 

webconfig配置如下:

.

.

 

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:

image

 

再设置下Service Behaviors:

image

 

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

 

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

 

 

 

 

 一步一步搭建客服系统

 

 

.



如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
posted @   疯吻IT  阅读(2906)  评论(5编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示