1. 程式人生 > >一步一步搭建客服系統 (4) 客戶列表 - JS($.ajax)調用WCF 遇到的各種坑

一步一步搭建客服系統 (4) 客戶列表 - JS($.ajax)調用WCF 遇到的各種坑

clu web operation script ont javascrip -1 mod ima

閱讀目錄

  • 1 創建WCF服務
  • 2 調用WCF
  • 3 配置
  • 4 遇到的各種坑

本文以一個生成、獲取“客戶列表”的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" />

一步一步搭建客服系統

一步一步搭建客服系統 (4) 客戶列表 - JS($.ajax)調用WCF 遇到的各種坑