[個人筆記] RESTful WCF 4.0 + AJAX JSONP實現跨域呼叫

  • 5306
  • 0
  • WCF
  • 2015-12-22

[個人筆記] RESTful WCF 4.0 + AJAX JSONP實現跨域呼叫

之前的.NET WCF 3.0在實現REST很痛苦,到3.5的時候,微軟特別發布了一個 WCF REST Starter Kit 套件,讓開發人員可以利用 WCF 3.5 開發 REST-based 應用程式。在 WCF 4.0 中,WCF 的核心已經融入了 REST Starter Kit 中的 URL 引擎,使用了類似MVC Routing來配置URL導向,雖然說現在開發已經非常容易上手,但在跨域呼叫時仍遇到些問題,本文紀錄開發過程與需注意細節。

※透過線上範本建立WCF REST Service

image

專案建立後可以看到相對以前的版本,新的模板少了很多東西,也很多部分的設定變簡單了

 

  • 少了svc文件,完全透過URL Routing來配置訪問路徑
  • 透過在Global.asax中配置類似ASP.NET的Routing來進行URL重定向
public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes();
    }

    private void RegisterRoutes()
    {
        // Edit the base address of Service1 by replacing the "Service1" string below
        RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
    }
}
  • web.config因為WCF Simple Configuration而大幅度的簡化了。

  • 因為已經融入了 REST Starter Kit 中的 URL 引擎與UriTemplate 整合進來,讓 Operation Contract 的方法可以由 URL 來指定,如同模板內建的service1.cs

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
    // GET /Service1/
    [WebGet(UriTemplate = "")]
    public List<SampleItem> GetCollection()
    {
        return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
    }

    //  POST /Service1/
    [WebInvoke(UriTemplate = "", Method = "POST")]
    public SampleItem Create(SampleItem instance)
    {
        throw new NotImplementedException();
    }

    // GET /Service1/100
    [WebGet(UriTemplate = "{id}")]
    public string Get(string id)
    {
        return "welcome";
    }

    // PUT /Service1/100
    [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
    public SampleItem Update(string id, SampleItem instance)
    {
        throw new NotImplementedException();
    }

    // DELETE /Service1/100
    [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
    public void Delete(string id)
    {
        // TODO: Remove the instance of SampleItem with the given id from the collection
        throw new NotImplementedException();
    }
}
 
※如何提供JSONP跨網域呼叫
  • 類別中添加[JavascriptCallbackBehavior(UrlParameterName="callback")]

image

  • web.config的 standardEndpoint 添加 crossDomainScriptAccessEnabled="true"

image

※AJAX叫用RESTful WCF


 

image

這段程式碼執行成功會先叫jsoncallback再進入success。

 

※參考資料一覽

RESTful 服務(配備 WCF)介紹

A Guide to Designing and Building RESTful Web Services with WCF 3.5

A Developer's Guide to the WCF REST Starter Kit

Introducing Windows Communication Foundation in .NET Framework 4

使用WCF 4.0 构建 REST Service

WCF REST Service with JSON

WCF REST Service with JSON Data

WCF 4 JSON REST Service

WCF 4.0 REST Service JSON跨域调用

[VS2010] WCF 4.0 新功能 (1): 簡易組態 (Simple Configuration)

[VS2010] WCF 4.0 新功能 (2): REST 服務開發

[VS2010] WCF 4.0 新功能 (3): 由 REST 服務中傳回自訂的格式