萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 呼叫 RESTful WCF 服務完整實作指南 (GET/POST 方法)

本文詳細介紹如何使用 jQuery 透過 AJAX 呼叫 RESTful 風格的 WCF 服務,涵蓋 GET 與 POST 兩種請求方式,並提供完整的伺服器端設定與用戶端程式碼範例,幫助開發者快速建立前後端分離的 Web 應用架構。

WCF 服務端核心設定

要讓 WCF 支援 RESTful 風格的 URI 並允許 AJAX 跨域呼叫,需完成兩項關鍵設定:

1. 修改 .svc 檔案指定 Factory

<%@ ServiceHost Language="C#" Debug="true" 
    Service="ajaxSample.HelloWorld" 
    CodeBehind="HelloWorld.svc.cs" 
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

說明: 若未指定 WebServiceHostFactory,WCF 將無法支援 https://localhost/HelloWorld.svc/Hello/person/name 這類 RESTful 風格的直接存取。

2. 移除 web.config 中的 <enableWebScript />

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="ajaxSample.HelloWorldAspNetAjaxBehavior">
        <!-- 移除或註解掉 enableWebScript -->
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
      multipleSiteBindingsEnabled="true" />
  <services>
    <service name="ajaxSample.HelloWorld">
      <endpoint address="" 
          behaviorConfiguration="ajaxSample.HelloWorldAspNetAjaxBehavior" 
          binding="webHttpBinding" 
          contract="ajaxSample.HelloWorld" />
    </service>
  </services>
</system.serviceModel>

服務端完整程式碼實作

using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace ajaxSample
{
    [ServiceContract(Namespace = "https://yjmyzz.cnblogs.com/")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class HelloWorld
    {
        /// 
        /// 僅支援 POST 的 RESTful 方法
        /// 
        [OperationContract]
        [WebInvoke(Method = "POST", 
            UriTemplate = "PostRestfulTest/{person}/{welcome}", 
            ResponseFormat = WebMessageFormat.Json)]
        public List<string> PostRestfulTest(string person, string welcome)
        {
            var result = new List<string>();
            result.Add("PostRestfulTest -> from server:");
            result.Add(person);
            result.Add(welcome);
            return result;
        }

        /// 
        /// 僅支援 GET 的 RESTful 方法
        /// 
        [OperationContract]
        [WebInvoke(Method = "GET", 
            UriTemplate = "GETRestfulTest/{person}/{welcome}", 
            ResponseFormat = WebMessageFormat.Json)]
        public List<string> GETRestfulTest(string person, string welcome)
        {
            var result = new List<string>();
            result.Add("GETRestfulTest -> from server:");
            result.Add(person);
            result.Add(welcome);
            return result;
        }

        /// 
        /// 同時支援 GET 與 POST 的 RESTful 方法
        /// 
        [OperationContract]
        [WebInvoke(Method = "*", 
            UriTemplate = "RestfulTest/{person}/{welcome}", 
            ResponseFormat = WebMessageFormat.Json)]
        public List<string> RestfulTest(string person, string welcome)
        {
            var result = new List<string>();
            result.Add("RestfulTest -> from server:");
            result.Add(person);
            result.Add(welcome);
            return result;
        }

        /// 
        /// 傳統 POST 方法 (需設定 BodyStyle)
        /// 
        [OperationContract]
        [WebInvoke(Method = "POST", 
            ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List<string> PostTest(string person, string welcome)
        {
            var result = new List<string>();
            result.Add("PostTest -> from server:");
            result.Add(person);
            result.Add(welcome);
            return result;
        }

        /// 
        /// 傳統 GET 方法
        /// 
        [OperationContract]
        [WebInvoke(Method = "GET", 
            ResponseFormat = WebMessageFormat.Json)]
        public List<string> GetTest(string person, string welcome)
        {
            var result = new List<string>();
            result.Add("GetTest -> from server:");
            result.Add(person);
            result.Add(welcome);
            return result;
        }
    }
}

關鍵屬性說明

  • WebInvoke:定義 HTTP 方法 (GET/POST/*)、URI 範本、回應格式 (JSON/XML)
  • UriTemplate:RESTful 風格的 URL 參數對應,大括號內參數會自動繫結到方法參數
  • BodyStyle:傳統 POST 需設為 WrappedRequest 或 Wrapped,否則參數無法正確繫結
  • ResponseFormat:建議統一使用 WebMessageFormat.Json 方便前端處理

前端 jQuery 呼叫範例

// RESTful GET 請求
$.getJSON('/HelloWorld.svc/GETRestfulTest/John/Welcome', function(data) {
    console.log('GET 回應:', data);
});

// RESTful POST 請求
$.ajax({
    url: '/HelloWorld.svc/PostRestfulTest/John/Welcome',
    type: 'POST',
    contentType: 'application/json',
    success: function(data) {
        console.log('POST 回應:', data);
    }
});

// 同時支援 GET/POST 的方法
$.ajax({
    url: '/HelloWorld.svc/RestfulTest/John/Welcome',
    type: 'POST', // 或 GET
    success: function(data) {
        console.log('通用方法回應:', data);
    }
});

常見問題與除錯提示

  1. 404 錯誤:檢查 .svc Factory 設定、UriTemplate 拼寫、IIS 是否啟用 ASP.NET 相容性
  2. 參數為 null:確認 UriTemplate 參數名稱與方法參數完全一致 (區分大小寫)
  3. 跨域問題:在 web.config 中設定 <httpProtocol><customHeaders><add name="Access-Control-Allow-Origin" value="*" /></customHeaders></httpProtocol>
  4. POST 參數接收不到:傳統模式務必加上 BodyStyle = WebMessageBodyStyle.WrappedRequest

掌握這些核心設定後,即可輕鬆建立支援 RESTful 風格的 WCF 服務,搭配 jQuery 實現流暢的前後端互動體驗。

copyright © 萬盛學電腦網 all rights reserved