DIV CSS 佈局教程網

用 jQuery 呼叫 RESTful WCF 服務的完整實作
編輯:JavaScript綜合知識     

本文示範如何讓 jQuery 直接呼叫 RESTful 風格的 WCF 服務,涵蓋 GET、POST 以及兩者皆可的情況,並說明一個保護敏感參數的實務技巧。

步驟一:改造 WCF 端

近年 RESTful 相當流行。為了讓 Ajax 能呼叫、同時支援 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 將無法用類似 https://localhost/helloWorld.svc/Hello/person/name 的 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>

步驟三:撰寫服務方法

[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)
    {
        return new List<string> { "PostRestfulTest -> from server:", person, welcome };
    }

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

    // GET 與 POST 皆可
    [OperationContract]
    [WebInvoke(Method = "*",
        UriTemplate = "RestfulTest/{person}/{welcome}",
        ResponseFormat = WebMessageFormat.Json)]
    public List<string> RestfulTest(string person, string welcome)
    {
        return new List<string> { "RestfulTest -> from server:", person, welcome };
    }

    // 常規 POST 方法:BodyStyle 必須設為 WrappedRequest 或 Wrapped
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public List<string> PostTest(string person, string welcome)
    {
        return new List<string> { "PostTest -> from server:", person, welcome };
    }

    // 常規 GET 方法
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    public List<string> GETTest(string person, string welcome)
    {
        return new List<string> { "GETTest -> from server:", person, welcome };
    }
}

幾個重點:UriTemplate 定義 RESTful 路徑模板,Method = "*" 表示不限請求方法;而POST 的非 RESTful 方法必須明確設定 BodyStyle = WrappedRequest,否則參數對不上。

步驟四:jQuery 端呼叫

$().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:必須自己序列化為 JSON 並指定 contentType
  $.ajax({
    url: "HelloWorld.svc/PostTest",
    type: "POST",
    contentType: "application/json",
    data: '{"person":"ccc","welcome":"ddd"}',
    dataType: "json",
    success: function (data) { alert("PostTest 呼叫成功:" + data); }
  });
});

注意最後一項:呼叫常規 POST 方法時,必須手動把資料序列化成 JSON 字串並設定 contentType: "application/json",否則 WCF 無法正確繫結參數。這與 RESTful 風格(參數在 URL 上)的呼叫方式有本質差異。

保護敏感參數:用 ashx 做中轉

有時候 WCF 暴露的方法需要一些敏感資訊作為參數(例如使用者名稱、使用者 ID)。若直接用 JS 呼叫 WCF,這些資訊會明文暴露在客戶端。這種場景下,常用一個伺服器端的 ashx 做中轉。

// TestService.svc —— 需要 userId 才能查詢
[ServiceContract]
public class TestService
{
    [OperationContract]
    public double GetSalary(int userId, int month)
    {
        return month == 1 ? 5000 : 1000;
    }
}
// AjaxProcess.ashx —— 前端只傳 month,userId 由伺服器端 session 決定
public class AjaxProcess : IHttpHandler
{
    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));

        context.Response.Write("{salary:" + salary + "}");
    }

    private int GetUserId() { return 1; }   // 實務上從 session 或權杖取得

    public bool IsReusable { get { return false; } }
}
// 前端只呼叫 ashx
$("#btnTest").click(function () {
  $.post("AjaxProcess.ashx", { month: 1 }, function (e) {
    var d = eval("(" + e + ")");
    alert(d.salary);
  }, "html");
});

幾點現代化建議

不要用 eval 解析 JSON。範例中的 eval("(" + e + ")") 是危險寫法,任意字串都能被當程式碼執行。請改用 JSON.parse(e),或在 jQuery 中直接指定 dataType: "json" 讓它自動解析。

ashx 中轉必須補上驗證。範例的 GetUserId() 寫死回傳 1,實作時一定要真正驗證身分(session、Cookie 或權杖),否則任何人都能查詢他人資料——這是一個典型的越權漏洞(IDOR)。

回應時明確指定 Content-Type。ashx 中若回傳 JSON,應設為 application/json; charset=utf-8 而非 text/plain,語意才正確。

最後,WCF 本身已進入維護狀態。若是新專案,建議直接採用 ASP.NET Web API 或最小化 API,路由、模型繫結與內容協商都是內建功能,不需要再手動處理 Factory、UriTemplate 與 BodyStyle 這些細節。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved