ajax请求wcf,JS($.ajax)调用WCF 遇到的各种坑

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

1 创建WCF服务

1.1 定义接口

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

0be121fa5b8988fbabbbc526af3b0fc0.gif

34031c708bfe702fe82d01ff5c6593aa.png[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 GetAll();

}

.

1.2 接口实现

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

.0be121fa5b8988fbabbbc526af3b0fc0.gif

34031c708bfe702fe82d01ff5c6593aa.png[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

[JavascriptCallbackBehavior(UrlParameterName = "callback")]

public class Queue : IQueue

{

static readonly ObjManager m_Queues;

static Queue()

{

m_Queues = new ObjManager();

}

public void Add(string roomName)

{

m_Queues.Add(roomName, new ClientQueue() { CreateTime = DateTime.Now });

}

public List GetAll()

{

return m_Queues.GetAllQueues().OrderBy(q => q.Value.CreateTime).Select(q => q.Key).ToList();

}

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

1.3 定义服务

添加一个wcf service, 就一行:

整体结构如下:

a69ed7a3f85de6d0fb8d03cb550e9f6a.png

.

2 调用WCF

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

.

0be121fa5b8988fbabbbc526af3b0fc0.gif

34031c708bfe702fe82d01ff5c6593aa.pngvar 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

});

.

客服端取所有的客户:

.

0be121fa5b8988fbabbbc526af3b0fc0.gif

34031c708bfe702fe82d01ff5c6593aa.png$.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配置如下:

.

0be121fa5b8988fbabbbc526af3b0fc0.gif

34031c708bfe702fe82d01ff5c6593aa.png

maxBufferSize="5242880" maxBufferPoolSize="5242880" maxReceivedMessageSize="5242880"

crossDomainScriptAccessEnabled="true" />

maxReceivedMessageSize="5242880" crossDomainScriptAccessEnabled="true">

bindingConfiguration="HttpBind" name="HttpBind" contract="Youda.WebUI.Service.Interface.IQueue" />

bindingConfiguration="HttpsBind" name="httpsBind" contract="Youda.WebUI.Service.Interface.IQueue" />

bindingConfiguration="HttpBind" name="HttpBind" contract="Youda.WebUI.Service.Interface.IChat" />

bindingConfiguration="HttpsBind" name="HttpsBind" contract="Youda.WebUI.Service.Interface.IChat" />

.

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 GetMsg(string clientID, int count);

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

先添加https的binding:

8b46b955d7fa9d8692f5c994d1723cd7.png

再设置下Service Behaviors:

d44a41eaa78f26a9560ef6e2a3128fd6.png

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

4.5 其它配置

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

maxBufferSize="5242880" maxBufferPoolSize="5242880" maxReceivedMessageSize="5242880"

crossDomainScriptAccessEnabled="true" />

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

bindingConfiguration="HttpBind" name="HttpBind" contract="Youda.WebUI.Service.Interface.IQueue" />

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值