Welcome to MSDN Blogs Sign in | Join | Help

Days with .NET Framework

.NET Framework 担当のプロダクトマーケティング 新村剛史の日記です。
JSON 形式でAJAX と連携するWCF サービス

皆さんこんにちは

ここ2回ほど、お知らせのエントリを書いていまして、またまた DEMO のフォローの間が空いてしまいました。今回は前回の REST スタイルな WCF の DEMO の内容を少し編集して、JSON 形式でデータを公開する方法。そして、それを ASP.NET AJAX を使って呼び出す方法を説明します。

まず、 JSON について説明したいと思います。 JSON は JavaScript Object Notation の略で JavaScript の Object 表現形式をほとんどそのまま採用したデータ表現形式です。JSON 形式でデータを提供することにより、 JavaScript でのデータ操作が容易になります。 .NET Framework 3.5 では Web スタイルなWCF の一貫として REST スタイルの WCF に非常に近い実装で実現することができるようになりました。

それでは、DEMO の説明に入っていきたいと思います。まず、前回使用した Contract からWebGet の部分を削除します。あと、下記のコードでは前回のソースからネームスペースは変更してあります。 using ステートメントで System.ServiceModel.Web を設定している以外は一般的な WCF のContract と同様です。

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web

namespace WCFJsonDemo
{
   
    [ServiceContract]
    public interface ISimpleService
    {
        [OperationContract]
         Customer GetCustomer(string id);
    }
 
    [DataContract]
    public struct Customer
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string City { get; set; }
        [DataMember]
        public string Country { get; set; }
    }
}
 

続いて、web.config です。endpointBehaviors → behavior の下に enableWebScript 要素を追加します。前回は webHttp だったところです。

<system.serviceModel>
 <services>
    <service name="WCFJsonDemo.SimpleService" >
      <endpoint
          address="/"
          binding="webHttpBinding" 
          behaviorConfiguration="jsonBehavior"
          contract="WCFJsonDemo.ISimpleService"/>
    </service>
 </services>
 <behaviors>
  <endpointBehaviors>
   <behavior name="jsonBehavior">
    <enableWebScript/>
   </behavior>
  </endpointBehaviors>
 </behaviors>
</system.serviceModel> 

あとはサービスの実装ですが、これは前回とネームスペース以外全く同じものを使用します。

using System;
using System.Collections.Generic;

namespace WCFJsonDemo
{
    public class SimpleService : ISimpleService
    {
        private List<Customer> customers = new List<Customer>{ 
                new Customer(){Id=1,Name="Masami", Country="Japan", City="Kanagawa"},
                new Customer(){Id=2,Name="Kazuhiko", Country="Japan", City="Tokyo"},
                new Customer(){Id=3,Name="Tomoyuki",Country="Japan", City="Tokyo"},
                new Customer(){Id=4,Name="Takeshi",Country="Japan",City="Kanagawa"},
                new Customer(){Id=5,Name="Steve",Country="USA",City="Redmond"},
                new Customer(){Id=6,Name="Bill",Country="USA",City="Redmond"}
            };

        public Customer GetCustomer(string id)
        {
            foreach (Customer customer in customers)
            {
                if (customer.Id == Int32.Parse(id)) return customer;
               
            }
            throw new Exception();
        }

    }
}

前回も申し上げましたが、非常に安易な実装ですが本質とは異なる部分なので目をつぶってください。

これでサービスの設定は出来ました。次はクライアントです。

下の aspx ファイルで ScriptManager というタグに注目してください。こちらのタグで今回のサービスである Path を設定してサービスの Proxy 経由で JavaScript からのサービス呼び出しを可能にしています。tempuri.org.ISimpleService.GetCustomer(id,onSuccess,onError) という形で Proxy 経由でContract で定義したメソッドを呼び出します。ただし、引数が Contract で定義された引数と異なることに注意してください。これはAJAX の名前の元となった Asynchronous と言う通り非同期で結果が返ってきます。結果が返ってきた場合に実行する関数を成功時と失敗時のそれぞれを引数として渡します。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AjaxJsonDemo._Default" %>
<!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 runat="server">
    <title>Json Demo</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
 
function Button1_onclick() {
    var id = document.getElementById('Text1').value
    tempuri.org.ISimpleService.GetCustomer(id,onSuccess,onError)
}
 
function onSuccess(arg1)
{
    val = arg1.Id + '\n' + arg1.Name + '\n' + arg1.City;
    document.getElementById('TextArea1').value = val;
}
function onError(arg1)
{
    alert(arg1);
}
// ]]>
</script>
    <style type="text/css">
        #TextArea1
        {
            height: 103px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <services>
            <asp:servicereference Path="SimpleService.svc" />
        </services>
    </asp:ScriptManager>
    </form>
    <p>
        <input id="Text1" type="text" /><input id="Button1" type="button"
            value="button" onclick="return Button1_onclick()" /></p>
    <p>
        <textarea id="TextArea1" cols="20" name="S1"></textarea></p>
</body>
</html>

 このように非常に簡単に JSON 形式のサービスを ASP.NET AJAX を使って呼び出すことができます。また、ASP.NET AJAX で使っている Proxy がどのようなものか確認したい場合は下記のURL を叩くことで確認することができます。

http://localhost:適切なポート番号/SimpleService.svc/js

JSON 形式のサービスを公開することも、ASP.NET AJAX を使用して呼び出すことも非常に簡単です。ぜひ、お試しください。

次回は RSS/ATOM のフィードについてご紹介したいと思います。

Posted: Wednesday, October 10, 2007 8:42 PM by tashinmu

Comments

Anonymous comments are disabled
Page view tracker