近幾年 RESTful 風格相當流行。為了讓 ajax 能直接呼叫,同時支援 /Hello/person/name 這類 RESTful URI,建立 Ajax-enabled WCF Service 之後必須手動修改 svc 檔,指定 Factory:
<%@ ServiceHost Language="C#" Debug="true" Service="ajaxSample.HelloWorld"
CodeBehind="HelloWorld.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>如果不加 Factory,WCF 就無法用 RESTful 方式直接訪問。
同時要把 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>以下用四種常見情境示範:只收 POST、只收 GET、兩者皆可,以及傳統(非 RESTful)的 GET/POST。
[ServiceContract(Namespace = "https://example.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> { "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) { ... }
// GET / POST 皆可
[OperationContract]
[WebInvoke(Method = "*", UriTemplate = "RestfulTest/{person}/{welcome}",
ResponseFormat = WebMessageFormat.Json)]
public List<string> RestfulTest(string person, string welcome) { ... }
// 只能 POST 的傳統方法(BodyStyle 需為 WrappedRequest)
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public List<string> PostTest(string person, string welcome) { ... }
// 只能 GET 的傳統方法
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public List<string> GETTest(string person, string welcome) { ... }
}幾個重點:UriTemplate 定義了 URL 中參數的位置,這些參數會自動對應到方法簽章;Method = "*" 表示同時接受 GET 與 POST;而傳統(非 RESTful)方法不帶 UriTemplate,參數改由 query string 或 request body 傳入,POST 時 BodyStyle 建議設為 WrappedRequest。
$().ready(function () {
$.post("HelloWorld.svc/PostRestfulTest/111/222", function (data) {
alert("PostRestfulTest 調用成功:" + data);
});
$.get("HelloWorld.svc/GETRestfulTest/333/444", function (data) {
alert("GETRestfulTest 調用成功:" + data);
});
$.get("HelloWorld.svc/RestfulTest/555/666", function (data) {
alert("RestfulTest(GET):" + data);
});
$.post("HelloWorld.svc/RestfulTest/777/888", function (data) {
alert("RestfulTest(POST):" + data);
});
// 傳統 GET:參數以物件傳入
$.get("HelloWorld.svc/GETTest", { person: "aaa", welcome: "bbb" }, function (data) {
alert("GETTest 調用成功:" + data);
});
// 傳統 POST:需手動指定 contentType 並序列化 body
$.ajax({
url: "HelloWorld.svc/PostTest",
type: "POST",
contentType: "application/json",
data: '{"person":"ccc","welcome":"ddd"}',
dataType: "html",
success: function (data) { alert("PostTest 調用成功:" + data); }
});
});有些時候,WCF 暴露的方法需要使用者 ID 這類敏感資訊作為參數。如果直接用 JavaScript 呼叫,這些資訊就會明文暴露在客戶端。常見的解法是在中間加一層 ashx 由伺服器端補上。
// TestService.svc
[ServiceContract]
public class TestService
{
[OperationContract]
public double GetSalary(int userId, int month)
{
return (month == 1) ? 5000 : 1000;
}
}// AjaxProcess.ashx
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string month = context.Request["month"];
TestService wcf = new TestService();
double salary = wcf.GetSalary(GetUserId(), int.Parse(month)); // userId 在伺服器端取得
context.Response.Write("{\"salary\":" + salary + "}");
}
private int GetUserId() { return 1; } // 實際上應從工作階段或權杖解出// jQuery 呼叫 ashx
$("#btnTest").click(function () {
$.post("AjaxProcess.ashx", { month: 1 }, function (e) {
var d = eval("(" + e + ")");
alert(d.salary);
}, "html");
});這個模式在企業系統中很常見:前端只傳業務參數,身分識別一律由伺服器端決定。要注意範例中的 eval 是為了求簡,正式環境請改用 $.parseJSON() 或直接指定 dataType: "json",並在 ashx 中正確設定 Content-Type 為 application/json。