WCF Ajax Web Service を使用すると バックエンドで WCF サービス を使用する AJAX が簡単に作成できます。 WCF Ajax Web Service を html などの ASP.NET ではないコンテンツから使用できる方法を記載します。
動作確認環境
- 動作環境:.NET 3.5, IIS 6
- 開発環境:Visual Studio 2008 SP1 Professional
1. WCF サービスを作成する
最初に WCF Ajax Web Service 用の WCF サービスを作成します。機能としてはWCF Sample 017:WCF で AJAX Serviceを作成してみる。 で作成したものと同じもサービスです。
1.1 プロジェクトの作成
WCF サービスをプロジェクトテンプレートとして、プロジェクトを作成します。プロジェクト名は WcfTest として説明を記述します。既定で作成されるIService1.cs, Service1.svc, Service.svc.cs を削除します。
1.1 PersonService サービスの作成
最初にモデルクラスを作成します。プロジェクトにPerson.cs というクラスを作成します。単純なデータ転送用のクラスです。
namespace WcfTest { [DataContract] public class Person { public Person(int id, string firstname, string lastname) { ID = id; FirstName = firstname; LastName = lastname; } [DataMember] public int ID; [DataMember] public string FirstName = string.Empty; [DataMember] public string LastName = string.Empty; } }
次に プロジェクトから新規項目を追加します。テンプレートにWCFサービスを選択肢、 PersonService を作成します。
サービスコントラクト IPersonService.cs を次のように編集します。
namespace WcfTest { // メモ: ここでインターフェイス名 "IPersonService" を変更する場合は、Web.config で "IPersonService" への参照も更新する必要があります。 [ServiceContract(Namespace="Wcf.PersonService")] public interface IPersonService { [OperationContract] [WebGet] IList<Person> GetPersons(); [OperationContract] [WebGet] Person GetParsonByID(int id); } }
サービスクラス PersonService.svc.cs を次のように編集します。GerPersons, GetParsenByID を実装しています。サンプルとして使用するために定義しています。
namespace WcfTest { // メモ: ここでクラス名 "PersonService" を変更する場合は、Web.config で "PersonService" への参照も更新する必要があります。 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class PersonService : IPersonService { private static IList<Person> _persons = new List<Person>(); static PersonService() { _persons.Add(new Person(1, "AAaiueo", "AUIEO")); _persons.Add(new Person(2, "kakikukeko", "KAKIKUKEKO")); _persons.Add(new Person(3, "sashisuseso", "SASHISUSESO")); } #region IPersonService メンバ public IList<Person> GetPersons() { return _persons; } public Person GetParsonByID(int id) { return _persons.FirstOrDefault(x => x.ID == id); } #endregion } }
1.3 Web.config の編集
WCF Ajax Web Service として動作するようにWeb.configを編集します。 behavior をenableWebScript に設定、 バインディングを webHttpBinding となるように設定を変更しています。
<system.serviceModel> <services> <service behaviorConfiguration="WcfTest.PersonServiceBehavior" name="WcfTest.PersonService"> <endpoint address="" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="WcfTest.IPersonService" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="AjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="WcfTest.PersonServiceBehavior"> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
2. html から WCF Ajax Web Service を使用する
2.1 ASP.NET Ajax Library をダウンロードしてプロジェクトに設定する
Microsoft Ajax Library を以下のサイトからダウンロードします。本記事では、 2009/11/17 stable 版をダウンロードして動作確認をしています。
- Microsoft ASP.NET Ajax Library (記事作成時点で最新版はASP.NET Ajax Library 0911 Beta,2009/11/17 stable)
http://ajax.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35895
- Microsoft ASP.NET AjaxLibrary (ASP.NET Ajax Extention 1.0 に該当をダウンロードする場合)
http://www.asp.net/ajax/downloads/library/
ダウンロードした zip ファイルを解凍して、Scriptsフォルダの MicrosoftAjax.js と MicrosoftAjaxWebForms.js を WCFサービスプロジェクトに js フォルダを作成しコピーします。プロジェクトに含めることを忘れないでください。
2.2 html から WCF Ajax Web Service を呼び出す
2とおりの方法で html から WCF Ajax Web Service を使用できるように html ファイルを作ってみました。 プロジェクトに WcfStatic.html と WcfStatic2.html を作成してそれぞれ次のように編集します。
以下が、 WcfStatic.html です。 javascript 実行時に js ファイルを取得してから、 Wcf Ajax Web Service のクライアント側のプロキシを使用して Wcf Ajax Web Service を利用しています。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>WCF Ajax Web Service を html で使用する</title> <script type="text/javascript"> function load() { var xmlreq = new XMLHttpRequest(); xmlreq.open('GET', 'js/MicrosoftAjax.js', false); xmlreq.send('') eval(xmlreq.responseText); xmlreq = new XMLHttpRequest(); xmlreq.open('GET', 'PersonService.svc/js', false); xmlreq.send('') eval(xmlreq.responseText); var proxy = new Wcf.PersonService.IPersonService(); proxy.GetParsonByID(1, onSuccess, onFail, null); } function onSuccess(result){ document.getElementById("txtId").value = result.ID; document.all.txtName.value = result.FirstName; // Microsoft AJAX Library 1.0 の MicrosoftAjax.js を使用する場合は // result.d.ID というように d が必要です。 // document.getElementById("txtId").value = result.d.ID; } function onFail(result){ } </script> </head> <body> <p>静的コンテンツ(html)から、 WCF Ajax Web Service を呼び出す方法</p> <input id="txtId" type="text" /> <input id="txtName" type="text" /> <input id="btnId" type="button" value="おして!!" onclick="javascript:load()" /> </body> </html>
次に、以下が WcfStatic2.html です。script タグを使用して、 js/MicrosoftAjax.js, js/MicrosoftAjaxWebForms.js を設定して、WCF Ajax Web Service を使用しています。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>WCF Ajax Web Service を html で使用するその2</title> <script type="text/javascript" src="js/MicrosoftAjax.js"></script> <script type="text/javascript" src="js/MicrosoftAjaxWebForms.js"></script> <script type="text/javascript" src="PersonService.svc/js"></script> <script type="text/javascript"> function load() { var proxy = new Wcf.PersonService.IPersonService(); proxy.GetParsonByID(1, onSuccess, onFail, null); } function onSuccess(result){ document.getElementById("txtId").value = result.ID; document.all.txtName.value = result.FirstName; // Microsoft AJAX Library 1.0 の MicrosoftAjax.js を使用する場合は // result.d.ID というように d が必要です。 // document.getElementById("txtId").value = result.d.ID; } function onFail(result){ } </script> </head> <body> <p>静的コンテンツ(html)から、 WCF Ajax Web Service を呼び出す方法</p> <input id="txtId" type="text" /> <input id="txtName" type="text" /> <input id="btnId" type="button" value="おして!!" onclick="javascript:load()" /> </body> </html>
3. 実行結果
実行結果は次のようになります。
おしてボタンをクリックすると、値がセットされます。動作自体は WcfStatic.html, WcfStatic2.html ともに同じです。
4. まとめ
今回の説明は以上です。ASP.NET AJAX Library は ASP.NET に限らずhtmlページなどで使用できます。そのため、今回の紹介した方法で WCF Ajax Web Service を使用できます。
紹介した方法を使用すると、 Dynamics CRM の ISV配下に アドオンとして追加したhtmlもWCF Ajax Web Service を使用できます。ただし、Dynamics CRM Web Service を WCF サービス側で使用する場合は aspNetCompatibilityEnabled を true にする必要があります。
さんのコメント: さんのコメント: