本文詳細介紹如何使用 jQuery 透過 AJAX 呼叫 RESTful 風格的 WCF 服務,涵蓋 GET 與 POST 兩種請求方式,並提供完整的伺服器端設定與用戶端程式碼範例,幫助開發者快速建立前後端分離的 Web 應用架構。
要讓 WCF 支援 RESTful 風格的 URI 並允許 AJAX 跨域呼叫,需完成兩項關鍵設定:
<%@ 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 風格的直接存取。
<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;
}
}
}
WrappedRequest 或 Wrapped,否則參數無法正確繫結WebMessageFormat.Json 方便前端處理// 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);
}
});
<httpProtocol><customHeaders><add name="Access-Control-Allow-Origin" value="*" /></customHeaders></httpProtocol>BodyStyle = WebMessageBodyStyle.WrappedRequest掌握這些核心設定後,即可輕鬆建立支援 RESTful 風格的 WCF 服務,搭配 jQuery 實現流暢的前後端互動體驗。