Share via


チュートリアル : ASP.NET アプリケーション サービスの使用

更新 : 2007 年 11 月

ASP.NET は、クライアント アプリケーションがユーザー認証、ロール、およびプロファイルの各情報にアクセスできるようにする Web 上のアプリケーション サービスを提供します。この情報には、さまざまな言語で記述され、各種のオペレーティング システムで実行されるクライアント アプリケーションによってアクセスできます。唯一の要件は、これらのクライアントが SOAP 1.1 プロトコルを介して通信できることです。

このチュートリアルは、次のセクションに分かれています。

  • 第 1 部では、アプリケーション サービスを公開するように ASP.NET Web サイトを構成する方法を示します。

  • 第 2 部では、ユーザーの認証、ロール、およびプロファイルの各情報にアクセスする Windows コンソール アプリケーションをビルドする方法を示します。このチュートリアルでは、Windows コンソール アプリケーションをビルドしますが、ASP.NET アプリケーション サービスは、SOAP 形式のメッセージを送受信できるクライアント アプリケーションでも使用できます。

前提条件

このチュートリアルを実行するための要件は次のとおりです。

  • Visual Studio 2008. このチュートリアルでは、Visual Web Developer Express Edition でサポートされていない Windows コンソール アプリケーションを作成するので、Microsoft Visual Web Developer 2005 を使用することはできない。

  • 使用するコンピュータに Microsoft SQL Server または SQL Express Edition がインストールされている。

アプリケーション サービスの公開

ここでは、ネットワーク上のすべてのクライアントからアクセスできるように、アプリケーション サービスを ASP.NET Web サイトの一部として公開する方法について説明します。ここで説明する手順は、サーバーにのみ適用されます。

メモ :

このチュートリアルでは、ファイル システム Web サイトを使用する必要があります。また、このチュートリアルは、IIS ではなく ASP.NET 開発サーバーを使用してサンプルを実行することを前提としています。詳細については、「Visual Web Developer における Web サーバー」を参照してください。

アプリケーション サービスの Web サイトを作成するには

  1. Visual Studio 2008 を開きます。

  2. [ファイル] メニューの [新しい Web サイト] をクリックします。

    [新しい Web サイト] ダイアログ ボックスが表示されます。

  3. [Visual Studio にインストールされたテンプレート] の [ASP.NET Web サイト] をクリックします。

  4. [場所] ボックスの一覧の [ファイル システム] をクリックします。

  5. [フォルダ] ボックスに、Web サイト名として「WcfApplicationServices」と入力します。

    メモ :

    任意の名前を使用できます。別の名前を使用する場合は、後でこのチュートリアルで必要に応じて名前を置き換えられるように、その名前をメモします。

  6. [OK] をクリックします。

    Visual Studio により新しい ASP.NET Web サイトが作成され、Default.aspx ページが表示されます。

  7. ソリューション エクスプローラで、Web サイトの名前をクリックし、F4 キーを押し、[プロパティ] ウィンドウを開きます。

  8. [プロパティ] ウィンドウで、[動的ポートの使用] を False に設定します。

    これにより、Visual Studio は、ASP.NET 開発サーバーを起動するときに、ランダムに選択されたポートではなく固定ポートを指定するように設定されます。このチュートリアルでは、クライアント プロキシ クラスと構成ファイルを生成するときに使用できる固定ポート番号を使用する必要があります。詳細については、「方法 : ASP.NET 開発サーバーのポートを指定する」を参照してください。

    メモ :

    プロパティ ページのウィンドウから [Web サイトのプロパティ] ウィンドウを開くことはできません。

  9. [ポート番号] を 8080 に設定します。

    メモ :

    使用されていないポートであればどのポートでも使用できます。別のポートを使用する場合は、後でこのチュートリアルでポート番号を 8080 に置き換えられるように、その番号をメモします。

ASP.NET メンバシップ、ロール、およびプロファイルの各情報はデータベースに格納されます。このデータベースは、必要なときに自動的に作成されます。次の手順では、アプリケーションのユーザーとロールを作成します。これにより、データベースが自動的に作成されます。

ユーザーとロール情報を作成するには

  1. Web サイトに Global.asax ファイルを追加し、ファイル内で、既存の Application_Start メソッドを次のコードに置き換えます。

    <%@ Application Language="VB" %>
    
    <script runat="server">
    
        Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs on application startup
            ' Warning. This code is just for test purposes 
            ' to generate a SQL Express database quickly.
            ' In a production environment, you must set 
            ' a SQL standard database separately.
            If Not Roles.RoleExists("Administrators") Then
                Roles.CreateRole("Administrators")
            End If
            If Not Roles.RoleExists("Friends") Then
                Roles.CreateRole("Friends")
            End If
        End Sub
    
    
    </script>
    
    
    <%@ Application Language="C#" %>
    
    <script runat="server">
    
        void Application_Start(object sender, EventArgs e) 
        {
            // Code that runs on application startup
            // Warning. This code is just for test purposes 
            // to generate a SQL Express database quickly.
            // In a production environment, you must set   3-25
            // a SQL standard database separately.
            if (!Roles.RoleExists("Administrators")){
                Roles.CreateRole("Administrators");
    
            }
            if (!Roles.RoleExists("Friends")){
                Roles.CreateRole("Friends");
    
            }
    
        }
    
    
    </script>
    
    

    Web アプリケーションを初めて実行するとき、このコードにより Aspnetdb.mdf ローカル データベースが作成され、Administrators ロールと Friends ロールがこのデータベースに追加されます。このデータベースは、ユーザー資格情報、ロール、およびプロファイル情報の格納に使用されます。

  2. Default.apx ページを開き、次のマークアップを追加します。これにより、ログイン ページ、プロファイル情報ページ、および新しいユーザー ページへのリンクが追加されます。これらのページは、後でこのチュートリアルで追加します。

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_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 id="Head1" runat="server">
        <title>Application Services Home Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h2>Enter Users' Information</h2>
    
            The following selections enable you to create users, and assign them roles and
            profile information.
    
            <p>
                <asp:Label ID="LoggedId"  Font-Bold="true" ForeColor="red" runat="server"/>
            </p>
    
            <table border="1">
                <tr>
                    <td align="left">Login to change profile</td>
                    <td align="left"><asp:LoginStatus ID="LoginStatus1" runat="server" /></td>
                </tr>
                <tr>
                    <td align="left">Define profile information (you must login first)</td>
                    <td align="left"><a href="Profile.aspx" target="_self">Profile Information</a></td>
                </tr>
                <tr>
                    <td align="left">Create user and assign role</td>
                    <td align="left"><a href="CreateUser.aspx"target="_self">New User</a></td>
                </tr>
    
             </table>
        </div>
    
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Application Services Home Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h2>Enter Users' Information</h2>
    
        The following selections enable you to create users, and assign them roles and
            profile information.
    
            <p>
                <asp:Label ID="LoggedId"  Font-Bold="true" ForeColor="red" runat="server"/>
            </p>
    
            <table border="1">
                <tr>
                    <td align="left">Login to change profile</td>
                    <td align="left"><asp:LoginStatus ID="LoginStatus1" runat="server" /></td>
                </tr>
                <tr>
                    <td align="left">Define profile information (you must login first)</td>
                    <td align="left"><a href="Profile.aspx" target="_self">Profile Information</a></td>
                </tr>
                <tr>
                    <td align="left">Create user and assign role</td>
                    <td align="left"><a href="CreateUser.aspx"target="_self">New User</a></td>
                </tr>
    
             </table>
        </div>
    
        </form>
    </body>
    </html>
    
  3. Default.aspx 分離コード ファイルで、Page_Load メソッドに、ユーザーが認証されているかどうかをチェックするコードを追加します。

    認証済みユーザーをチェックする方法の例を次に示します。

    Imports System
    Imports System.Data
    Imports System.Configuration
    Imports System.Collections
    Imports System.Web
    Imports System.Web.Security
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports System.Web.UI.HtmlControls
    
    Partial Public Class _Default
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                LoggedId.Text = HttpContext.Current.User.Identity.Name + " you are logged in"
            End If
    
        End Sub
    End Class
    
    
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                LoggedId.Text = HttpContext.Current.User.Identity.Name +
                    " you are logged in";
            }
    
        }
    }
    
  4. Login.aspx という名前のページを追加します。[別のファイルにコードを書き込む] がオンになっていることを確認します。

  5. Login コントロールを Login.aspx ファイルに追加します。

    Login.aspx ファイルのマークアップを次の例に示します。

    <%@ Page Language="VB" AutoEventWireup="true" %>
    
    <!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>Login Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Login ID="Login1"   runat="server" />
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" %>
    
    <!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>Login Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Login ID="Login1"   runat="server"/>
        </div>
        </form>
    </body>
    </html>
    
  6. Profile.aspx という名前のページを追加し、[別のファイルにコードを書き込む] がオンになっていることを確認します。

  7. 次のマークアップを Profile.aspx ページに追加します。

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Profile.aspx.vb" Inherits="_Profile" %>
    
    <!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 id="Head1" runat="server">
        <title>Profile Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h3>Current Authenticated User Profile Information</h3> 
    
            <a href="Default.aspx">back to default page</a>
    
            <h4>Read Profile Information</h4>
            <table>
                <tr>
                    <td align="left">User Name</td>
                    <td align="left">
                        <asp:Label ID="Label1" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">User Roles</td>
                    <td align="left">
                        <asp:Label ID="Label2" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">First Name</td>
                    <td>
                        <asp:Label ID="Label3" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td>    
                        <asp:Label ID="Label4" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td>    
                        <asp:Label ID="Label5" runat="server" Text="Label"/>
                    </td>
                </tr>
    
            </table>
            <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
                Text="Read Profile Information" />
    
            <hr />
    
            <h3>Update Profile Information </h3>
    
            <table>
                <tr>
                    <td align="left">First Name</td>
                    <td align="left"><asp:TextBox ID="TextBox1" runat="server"/></td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td align="left"><asp:TextBox ID="TextBox2" runat="server"/></td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td align="left"><asp:TextBox ID="TextBox3" runat="server"/></td>
                </tr>
    
            </table>
    
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Update Profile Data" />
    
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="Profile.aspx.cs" Inherits="ProfileInformation" %>
    
    <!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 id="Head1" runat="server">
        <title>Profile Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h3>Current Authenticated User Profile Information</h3> 
    
            <a href="Default.aspx">back to default page</a>
    
            <h4>Read Profile Information</h4>
            <table>
                <tr>
                    <td align="left">User Name</td>
                    <td align="left">
                        <asp:Label ID="Label1" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">User Roles</td>
                    <td align="left">
                        <asp:Label ID="Label2" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">First Name</td>
                    <td>
                        <asp:Label ID="Label3" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td>    
                        <asp:Label ID="Label4" runat="server" Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td>    
                        <asp:Label ID="Label5" runat="server" Text="Label"/>
                    </td>
                </tr>
    
            </table>
            <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
                Text="Read Profile Information" />
    
            <hr />
    
            <h3>Update Profile Information </h3>
    
            <table>
                <tr>
                    <td align="left">First Name</td>
                    <td align="left"><asp:TextBox ID="TextBox1" runat="server"/></td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td align="left"><asp:TextBox ID="TextBox2" runat="server"/></td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td align="left"><asp:TextBox ID="TextBox3" runat="server"/></td>
                </tr>
    
            </table>
    
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Update Profile Data" />
    
        </div>
        </form>
    </body>
    </html>
    

    Profile ページには、ユーザーの名前とロールを表示するのに使用される Label コントロールと、ユーザーの名前と ID を変更するのに使用される TextBox コントロールが含まれます。

  8. Profile.aspx ページの分離コード ファイルに次のコードを追加します。

    Imports System
    Imports System.Data
    Imports System.Configuration
    Imports System.Collections
    Imports System.Web
    Imports System.Web.Security
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports System.Web.UI.HtmlControls
    
    Partial Public Class _Profile
        Inherits System.Web.UI.Page
    
        Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    
             Dim Profile As ProfileCommon = TryCast(HttpContext.Current.Profile, ProfileCommon)
    
            If HttpContext.Current.User.Identity.IsAuthenticated Then
    
                Label1.Text = HttpContext.Current.User.Identity.Name
                Dim roles As String() = _
                    System.Web.Security.Roles.GetRolesForUser()
    
                Label2.Text = ""
                For Each r As String In roles
                    Label2.Text += r + " "
                Next
    
                Label3.Text = Profile.FirstName()
                Label4.Text = Profile.LastName
    
                Label5.Text = Profile.EmployeeId
            Else
                Label1.Text = "User is not Authenticated"
                Label1.ForeColor = System.Drawing.Color.Red
            End If
        End Sub
    
        Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                Label1.Text = HttpContext.Current.User.Identity.Name
                Dim roles As String() = _
                    System.Web.Security.Roles.GetRolesForUser()
                Label2.Text = ""
                For Each r As String In roles
                    Label2.Text += r + " "
                Next
                Label3.Text = Profile.FirstName
                Label4.Text = Profile.LastName
                Label5.Text = Profile.EmployeeId
            Else
                Label1.Text = "User is not Authenticated"
                Label1.ForeColor = System.Drawing.Color.Red
            End If
        End Sub
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                Profile.FirstName = TextBox1.Text
                Profile.LastName = TextBox2.Text
                Profile.EmployeeId = TextBox3.Text
            End If
        End Sub
    End Class
    
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class ProfileInformation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
         ProfileCommon Profile = HttpContext.Current.Profile
                                      as ProfileCommon;
    
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Label1.Text = HttpContext.Current.User.Identity.Name;
                string[] roles = Roles.GetRolesForUser();
                Label2.Text = "";
                foreach (string r in roles)
                {
                    Label2.Text += r + " ";
                }
    
                Label3.Text = Profile.FirstName;
                Label4.Text = Profile.LastName;
                Label5.Text = Profile.EmployeeId;
    
            }
            else
            {
                Label1.Text = "User is not Authenticated";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }
    
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Label1.Text = HttpContext.Current.User.Identity.Name;
                string[] roles = Roles.GetRolesForUser();
                Label2.Text = "";
                foreach (string r in roles)
                {
                    Label2.Text += r + " ";
                }
    
                Label3.Text = Profile.FirstName;
                Label4.Text = Profile.LastName;
                Label5.Text = Profile.EmployeeId;
    
            }
            else
            {
                Label1.Text = "User is not Authenticated";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Profile.FirstName = TextBox1.Text;
                Profile.LastName = TextBox2.Text;
                Profile.EmployeeId = TextBox3.Text;
            }
        }
    }
    
    メモ :

    前の例では、Profile インスタンスとの競合を防ぐために、分離コード ファイルのクラス名が _Profile に変更されています。

    このページ内のコードにより、ユーザー プロファイル情報を取得および変更できます。

    メモ :

    Web サイトのプロファイル プロパティを有効にするまで、プロジェクトはコンパイルされません。この操作は次の手順で行います。

  9. CreateUser.aspx ページという名前のページを追加し、次のマークアップを追加します。

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="CreateUser.aspx.vb" Inherits="CreateUser" %>
    
    <!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>Add New User</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
    
            <h2>Add New User</h2>
    
            <a href="Default.aspx">back to default page</a>
    
            <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
              OnCreatedUser="On_CreatedUser">
                <wizardsteps>
                    <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server"  />
                    <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"  />
                </wizardsteps>
            </asp:CreateUserWizard>
            <p> 
                Check the following box to assign the user to the administrator role.
                Otherwise, the user will be assigned to the friends role by default. 
            </p>
            <span style="font-weight:bold; color:Red">Administrator</span> 
            <asp:CheckBox ID="CheckBox1" runat="server" />
    
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="CreateUser.aspx.cs" Inherits="CreateUser" %>
    
    <!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 id="Head1" runat="server">
        <title>Add New User</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
    
            <h2>Add New User</h2>
    
            <a href="Default.aspx">back to default page</a>
    
            <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
              OnCreatedUser="On_CreatedUser">
                <wizardsteps>
                    <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server"  />
                    <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"  />
                </wizardsteps>
            </asp:CreateUserWizard>
            <p> 
                Check the following box to assign the user to the administrator role.
                Otherwise, the user will be assigned to the friends role by default. 
            </p>
            <span style="font-weight:bold; color:Red">Administrator</span> 
            <asp:CheckBox ID="CheckBox1" runat="server" />
    
        </div>
        </form>
    </body>
    </html>
    
  10. CreateUser.aspx ページの分離コード ファイルに次のコードを追加します。

    Imports System
    Imports System.Data
    Imports System.Configuration
    Imports System.Collections
    Imports System.Web
    Imports System.Web.Security
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports System.Web.UI.HtmlControls
    
    Partial Public Class CreateUser
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    
        End Sub
    
        Protected Sub On_CreatedUser(ByVal sender As Object, ByVal e As EventArgs)
            Dim userName As String = CreateUserWizard1.UserName
            If CheckBox1.Checked Then
                HttpContext.Current.Response.Write(userName)
                Roles.AddUserToRole(userName, "Administrators")
            Else
                Roles.AddUserToRole(userName, "Friends")
            End If
    
            CheckBox1.Visible = False
    
            HttpContext.Current.Response.Redirect("~/default.aspx")
        End Sub
    End Class
    
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class CreateUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        protected void On_CreatedUser(object sender, EventArgs e)
        {
            string userName = CreateUserWizard1.UserName;
            if (CheckBox1.Checked)
            {
                HttpContext.Current.Response.Write(userName);
                Roles.AddUserToRole(userName, "Administrators");
            }
            else
                Roles.AddUserToRole(userName, "Friends");
    
            CheckBox1.Visible = false;
    
            HttpContext.Current.Response.Redirect("~/default.aspx");
        }
    }
    

    このページにより、ユーザーを作成してロールに割り当てることができます。

次の手順では、Web サイトでのフォーム認証、ロール、およびプロファイル プロパティを有効にします。この操作を行うには、Web.config ファイルの構成設定を使用します。

認証、ロール、およびプロファイル プロパティを構成するには

  1. Web サイトの Web.config ファイルを開きます。

  2. 次の例に示すように、system.web グループで、既定の Windows 認証をフォーム認証に変更します。

    <authentication mode="Forms" />
    
  3. 次の例に示すように、system.web グループで、roleManager 要素を追加してロール サービスを構成します。

    <roleManager enabled="true"/>
    
  4. 次の例に示すように、system.web グループで、profile セクションと properties 要素を使用してプロファイル サービスを構成します。

    <profile enabled="true">
      <properties>
        <add name="FirstName"   type="String"/>
        <add name="LastName"    type="String"/>
        <add name="EmployeeId"  type="String"/>
      </properties>
    </profile>
    

    このプロファイル設定により、ASP.NET プロファイル サービスで管理される 3 つのプロパティが定義されます。実行時には、これらのプロパティを含む ProfileCommon 型のクラスが動的に作成されます。

    必要な変更をすべて加えた Web.config ファイルの一部を次の例に示します。

    <system.web>
    <!-- Other settings. -->
    <authentication mode="Forms" />
    <roleManager enabled="true"/>
    <profile enabled="true">
      <properties>
        <add name="FirstName"   type="String"/>
        <add name="LastName"    type="String"/>
        <add name="EmployeeId"  type="String"/>
      </properties>
    </profile>
    </system.web>
    

ここで、後でログインに使用するユーザー情報を作成できます。

ユーザーを作成してプロファイル情報を割り当てるには

  1. ソリューション エクスプローラで Default.aspx ページを選択し、Ctrl キーを押しながら F5 キーを押して、ページを実行します。

    ブラウザにページが表示されます。アドレス バーには次の URL が表示されます。

    https://localhost:8080/WcfApplicationServices/Default.aspx
    
  2. [新しいユーザー] をクリックします。

    CreateUser.aspx ページが表示されます。

  3. ユーザーを作成し、定義済みのロールに割り当てます。この操作を行うには、まず、ユーザーの資格情報を入力し、[ユーザーの作成] をクリックします。

    作成したユーザー名とパスワードを記録しておきます。ユーザー名とパスワードは、ユーザーのプロファイル情報を割り当てる、または変更するときに必要になります。

    たとえば、ユーザー名が "joeA" のユーザーを作成し、joeA が Administrators ロールのメンバになるように、[Administrator] チェック ボックスをオンにします。ユーザー名が "joeNA" の 2 人目のユーザーを作成し、ここでは [Administrator] チェック ボックスをオフにしたままにします。ユーザー joeNA は Friends ロールのメンバになり、Administrators ロールのメンバにはなりません。Friends ロールと Administrators ロールは、Global.asax ファイル内の Application_Start メソッドに先に追加したコードによって作成されます。

    ユーザーを作成した後、Default.aspx ページにリダイレクトされます。

  4. Default.aspx ページで、[ログイン] をクリックします。

    Login.aspx ページが表示されます。

  5. 先ほど作成したユーザーのうち 1 人の資格情報を使用してログインします。

    ログインに成功すると、Default.aspx ページにリダイレクトされます。

  6. [プロファイル情報] をクリックします。

    Profile.aspx ページが表示されます。

  7. 名、姓、および識別番号を入力して、ログインしたユーザーのプロファイル情報を入力または更新します。

  8. [Update Profile Data] をクリックします。

  9. [Read Profile Information] をクリックします。

    入力した情報が表示されます。この手順で、プロファイル プロパティが機能していることを確認できます。

ユーザーとプロファイル情報の作成が完了しました。これで、この情報をクライアント アプリケーションで利用できるようになります。

アプリケーション サービスのマッピングと構成

ASP.NET アプリケーション サービスを使って作成したユーザー情報をここで公開できます。クライアントからユーザーの資格情報とプロファイル情報にアクセスする前に、アプリケーション サービスを指し示すマッピング ファイル (.svc) を作成する必要があります。これにより、SOAP メッセージを送受信できるプラットフォームで実行されているすべてのアプリケーションがサービスを使用できるようになります。アプリケーション サービスがネットワーク上で公開されるように Web サイトを構成する必要もあります。

アプリケーション サービスのマッピング ファイルを作成するには

  1. Web サイトに WCF サービス ファイル (.svc) を追加し、MyAuthenSvcWrap.svc という名前を付けます。

  2. 既存の @ ServiceHost ディレクティブを、System.Web.ApplicationServices.AuthenticationService クラスを参照する次のディレクティブに置き換えます。

    <%@ ServiceHost Language="VB"
      Service="System.Web.ApplicationServices.AuthenticationService" 
      Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" 
      Debug="true" %>
    
    <%@ ServiceHost Language="C#"
      Service="System.Web.ApplicationServices.AuthenticationService" 
      Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" 
      Debug="true" %>
    

    この例では、カスタム認証サービスは実装されません。その代わりに、組み込みの System.Web.ApplicationServices.AuthenticationService クラスが呼び出されます。

  3. App_Code ディレクトリ内のインターフェイス ファイルとクラス ファイル (App_Code\MyAuthenSvcWrap と App_Code\IMyAuthenSvcWrap) を削除します。

    .svc ファイルがプロジェクトに追加されたときに、インターフェイス ファイルとクラス ファイルが作成されています。System.Web.ApplicationServices.AuthenticationService サービスを使用し、カスタム サービスを実装しないので、これらのファイルは必要ありません。

  4. Web サイトに別の WCF サービス ファイル (.svc) を追加し、MyRoleSvcWrap.svc という名前を付けます。

  5. MyRoleSvcWrap.svc ファイルを開き、ファイルの内容を次の @ ServiceHost ディレクティブに置き換えます。これにより、System.Web.ApplicationServices.RoleService クラスへの参照が作成されます。

    <%@ ServiceHost Language="VB" 
       Service="System.Web.ApplicationServices.RoleService" 
       Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Language="C#" 
      Service="System.Web.ApplicationServices.RoleService" 
      Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
  6. App_Code ディレクトリで、MyRoleSvcWrap サービスのインターフェイス ファイルとクラス ファイルを削除します。

  7. Web サイトに別の WCF サービス ファイル (.svc) を追加し、MyProfileSvcWrap.svc という名前を付けます。

  8. MyProfileSvcWrap.svc ファイルを開き、ファイルの内容を次のディレクティブに置き換えます。これにより、System.Web.ApplicationServices.ProfileService クラスへの参照が作成されます。

    <%@ ServiceHost Language="VB"
      Service="System.Web.ApplicationServices.ProfileService" 
      Factory ="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Language="C#"
    Service="System.Web.ApplicationServices.ProfileService" 
    
    Factory ="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
  9. App_Code ディレクトリで、MyProfileSvcWrap サービスのインターフェイス ファイルとクラス ファイルを削除します。

  10. すべての .svc ファイルを保存して閉じます。

これで、アプリケーション サービスを公開するように Web アプリケーションを構成できます。

アプリケーション サービスを構成するには

  1. Web.config ファイルを開くか、切り替えます。

  2. configSections セクションの下に、新たに system.web.extensions セクションを追加します。

  3. scripting 要素で、webServices セクションを利用してアプリケーション サービスを有効にします。

    完成した system.web.extensions 要素を次の例に示します。

    </configSections>
    
    <system.web.extensions>
      <scripting>
        <webServices>
          <authenticationService enabled="true"
           requireSSL = "false"/>
          <profileService
              enabled="true"
              readAccessProperties="FirstName,LastName,EmployeeId"/>
          <roleService enabled="true"/>
        </webServices>
      </scripting>
    </system.web.extensions>
    
      <appSettings/>
    
  4. system.serviceModel セクションの子として、serviceHostingEnvironment 要素を追加し、その aspNetCompatibilityEnabled を true に設定します。

    完成した serviceHostingEnvironment 要素を次の例に示します。

    </runtime>
     <system.serviceModel>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    
  5. system.serviceModel グループで、クライアント アプリケーションが SOAP プロトコルを使用してアクセスできるようにアプリケーション サービスを構成します。その場合は、次の手順を実行します。

    1. system.serviceModel 要素から、name 属性が "MyAuthenSvcWrapBehavior" の <behaviors><serviceBehaviors><behavior> 要素を探します。

    2. behavior 要素の name 属性の値を "MyAuthenSvcWrapBehavior" から "AppServiceBehaviors" に変更します。このチュートリアルでは、3 つすべてのサービスに対して AppServiceBehaviors 動作を使用するようにアプリケーションを構成します。

    3. <system.serviceModel><behaviors><serviceBehaviors> 要素から、名前が "MyRoleSvcWrapBehavior" と "MyProfileSvcWrapBehavior" の behavior 要素を削除します。

    完成した <system.serviceModel> セクションを次の例に示します。

    </runtime>
     <system.serviceModel>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      <behaviors>
       <serviceBehaviors>
        <behavior name="AppServiceBehaviors">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
       </serviceBehaviors>
      </behaviors>
    
  6. "MyAuthenSvcWrapBehavior" という名前の <system.serviceModel><services><service> 要素で、behavior 要素の behaviorConfiguration 属性の値を "MyAuthenSvcWrapBehavior" から "AppServiceBehaviors" に変更します。

  7. name 属性の値を "MyAuthenSvcWrap" から "System.Web.ApplicationServices.AuthenticationService" に変更します。

  8. 次の手順を実行して、<service><endpoint> 要素を構成します。

    1. address 属性を削除します。

    2. binding 属性の値を "wsHttpBinding" から "basicHttpBinding" に変更します。

    3. contract 属性の値を "IMyAuthenSvcWrap" から "System.Web.ApplicationServices.AuthenticationService" に変更します。

    4. bindingNamespace 属性を追加し、"https://asp.net/ApplicationServices/v200" に設定します。

    5. 子 identity 要素を削除します。

    次の例に、認証 service 要素のマークアップを示します。

    <service
      behaviorConfiguration="AppServiceBehaviors" 
      name="System.Web.ApplicationServices.AuthenticationService">
        <endpoint binding="basicHttpBinding" 
      contract="System.Web.ApplicationServices.AuthenticationService"
          bindingNamespace="https://asp.net/ApplicationServices/v200"       
                   >
        </endpoint>
    </service>
    

    詳細については、「<service> 要素」を参照してください。

  9. MyAuthenSvcWrap 要素に対して手順 8. を繰り返します。

    完成した system.serviceModel 要素を次の例に示します。

    <system.serviceModel>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      <behaviors>
       <serviceBehaviors>
        <behavior name="AppServiceBehaviors">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
       </serviceBehaviors>
      </behaviors>
      <services>
        <service 
            behaviorConfiguration="AppServiceBehaviors" 
            name="System.Web.ApplicationServices.AuthenticationService">
          <endpoint  binding="basicHttpBinding" 
              contract="System.Web.ApplicationServices.AuthenticationService"
               bindingNamespace="https://asp.net/ApplicationServices/v200"       
                   />
        </service>
        <service 
            behaviorConfiguration="AppServiceBehaviors" 
            name="System.Web.ApplicationServices.RoleService">
          <endpoint  binding="basicHttpBinding" 
              contract="System.Web.ApplicationServices.RoleService"
              bindingNamespace="https://asp.net/ApplicationServices/v200"       
                   />
        </service>
        <service 
            behaviorConfiguration="AppServiceBehaviors" 
            name="System.Web.ApplicationServices.ProfileService">
          <endpoint  binding="basicHttpBinding"
              contract="System.Web.ApplicationServices.ProfileService"
              bindingNamespace="https://asp.net/ApplicationServices/v200"
                   />
        </service>
      </services>
     </system.serviceModel>
    </configuration>
    

これで、Windows クライアント アプリケーションで使用される認証サービスをアクティブにするために Web サイトを実行できます。これにより、アプリケーション サービス インフラストラクチャが正常に動作していることも確認できます。

Web サイトをアクティブにしてアプリケーション サービスを公開するには

  • ソリューション エクスプローラで MyAuthenSvcWrap.svc ファイルを右クリックし、[ブラウザで表示] をクリックします。

    Web サービスが呼び出され、サービスのテストに関する指示を示したページがブラウザに表示されます。サービス URL は、クライアント アプリケーションからサービスにアクセスするために次の手順で必要になるため、メモしておく必要があります。

    メモ :

    ブラウザは閉じないでください。ASP.NET 開発サーバーを使用している場合、アプリケーション サービスをアクティブにしておくために、ブラウザを開いたままにしておく必要があります。

これで、Web で使用できるように Web でアプリケーション サービスを構成しました。次の手順では、クライアント アプリケーションからこれらのサービスを呼び出します。

アプリケーション サービスの使用

ここでは、アプリケーション サービスにアクセスするために Windows コンソール アプリケーションの形式でクライアント アプリケーションを作成する方法について説明します。このアプリケーション サービスは、SOAP 形式でメッセージを送受信できる任意のクライアントからアクセスできます。

クライアント コンソール アプリケーションを作成するには、次の一般的な手順に従います。

  • クライアント アプリケーションを作成します。

  • アプリケーション サービス プロキシ ファイルと関連する構成ファイルを生成します。

  • 生成されたプロキシ ファイルと構成ファイルをクライアント アプリケーションに追加し、アプリケーションをコンパイルします。

  • 生成されたプロキシからアプリケーション サービス操作を呼び出します。

    メモ :

    認証資格情報などの機密のユーザー データをサービスに渡す場合は、HTTPS プロトコルを使用する SSL (Secure Sockets Layer) を使用します。たとえば、次の例では、authenticationService 要素の requireSSL 属性の値を "false" から "true" に変更します。詳細については、MSDN Web サイトの「トランスポート セキュリティ」および「HTTP Security and ASP.NET Web Services」、IIS Web サイトの「Configuring Secure Sockets Layer in IIS 7.0」を参照してください。

Windows コンソール アプリケーションを作成するには

  1. Visual Studio で、[ファイル] メニューの [追加] をポイントし、[新しいプロジェクト] をクリックします。

  2. 優先する言語を選択し、[Visual Studio にインストールされたテンプレート] で [コンソール アプリケーション] をクリックします。

  3. アプリケーションに AppSvcClient という名前を付け、アプリケーションの場所を入力し、[OK] をクリックします。

    Visual Studio は、プロジェクトを現在のソリューションに追加して、既定のクラス ファイルを開きます。

  4. コンソール アプリケーションの名前を右クリックし、[参照の追加] をクリックします。

  5. [参照の追加] ダイアログ ボックスで、[.NET] タブをクリックし、System.ServiceModel と System.Runtime.Serialization をクリックします。次に、[OK] をクリックします。

    これにより、プロキシ クラスの使用に必要なクラスを含むプロジェクトに名前空間が追加されます。

アプリケーション サービス用のプロキシ クラスと構成情報の生成

ここで、コンソール アプリケーションが AppSvcClient コンソール アプリケーションからアプリケーション サービスにアクセスできるようにするプロキシ クラスと構成情報を生成します。アプリケーション サービスごとにプロキシ クラスと構成を別々に生成します。

アプリケーション サービス用のプロキシ クラスを生成するには

  1. Windows の [スタート] ボタンをクリックし、[すべてのプログラム] をポイントします。次に、[Microsoft Visual Studio 2008] をポイントし、[Visual Studio Tools] をポイントし、[Visual Studio 2008 コマンド プロンプト] をクリックします。

    メモ :

    Microsoft Vista を実行している場合は、このコマンドを管理者として実行する必要があります。

    Windows のコマンド ウィンドウが開きます。環境設定に .NET Framework ツールへのパスが入っています。

  2. Windows のコマンド ラインで、AppSvcClient プロジェクトに使用する Program.cs ファイルまたは Module1.vb ファイルが含まれるディレクトリに移動します。

  3. サービス ユーティリティ ツール (Svcutil.exe) を使用して、認証サービス プロキシ クラスを生成します。手順 1. で開いた Windows コマンド ラインに、次のコマンドを入力します。

    svcutil https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"VB"
    
    svcutil https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"C#"
    
    メモ :

    既定の言語出力は C# です。/language:"VB" というフラグは、Visual Basic で出力する場合にのみ必要となります。

    値 "localhost:8080" は、このチュートリアルから Web サイトを実行するときに使用する URL と一致している必要があります。ASP.NET 開発サーバーに別のポート番号を使用した場合、または動的なポート割り当てを使用している場合は、適切な値に置き換えます。ポート番号を変更した場合は、Svcutil.exe ツールによって生成される .config ファイルを新しいポート番号と一致するように更新する必要があります。

    コマンド内の .svc ファイルの名前は、このチュートリアルの前半で .svc ファイルの作成に使用した名前と一致している必要があります。プロキシ クラス ファイルには任意の名前を付けることができます。この例では、プロキシ クラス名は対応する .svc ファイルの名前と一致しています。

  4. サービス ユーティリティ ツールによって生成された output.config 構成ファイルの名前を App.config に変更します。

  5. ソリューション エクスプローラで、コンソール アプリケーションの名前を右クリックし、[追加] をクリックします。次に、[既存の項目] をクリックし、生成した AuthenticationService プロキシ クラス ファイルを選択して、[追加] をクリックします。

  6. コンソール アプリケーションのメイン クラス ファイルで、テストを作成するために次のコードを追加します。

    Imports System.ServiceModel
    
    Module Module1
    
        Sub Main(ByVal args As String())
    
            If (args.Length <> 2) Then
                Console.WriteLine("missing args username password")
                Return
            End If
    
            Dim username As String = args(0)
            Dim password As String = args(1)
            Dim result As Boolean = False
            Dim customCredential As String = "Not Used by the default membership provider"
            Dim isPersistent As Boolean = True ' authentication ticket remains valid across sessions.
    
            'BasicHttpBinding and endpoint are provided in app.config file.
            Dim authService As New AuthenticationServiceClient()
    
            result = authService.Login(username, password, customCredential, isPersistent)
    
            If result Then
                Console.WriteLine("Welcome " + username + ". You have logged in.")
            Else
                Console.WriteLine("We could not validate your credentials.")
            End If
    
            Console.WriteLine("Enter any key to exit.")
            Console.Read()
    
        End Sub
    
    End Module
    
    using System;
    using System.Text;
    using System.ServiceModel;
    
    class Program {
    
        static void Main(string[] args) {
    
            if (args.Length < 1) {
                Console.WriteLine("missing args username password");
                return;
            }
    
            string username = args[0];
            string password = args[1];
            bool result = false;
    
            // BasicHttpBinding and endpoint are provided in app.config file
            AuthenticationServiceClient authService = new AuthenticationServiceClient();
            string customCredential = "Not Used by the default membership provider";
            bool isPersistent = true;  // authentication ticket remains valid across sessions.
    
            result = authService.Login(username, password, customCredential, isPersistent);
    
            if (result == true)
                Console.WriteLine("Welcome " + username + ". You have logged in.");
            else
                Console.WriteLine("Unable to login");
        }
    }
    

    このコードにより、コンソール アプリケーションから実行するときにサービスにユーザー名とパスワードを渡すことができるようになります。チュートリアルの前半で作成したユーザーとパスワードの値を使用できます。

    テスト アプリケーションは、App.config ファイルからバインディングとエンドポイントの情報を取得します。

  7. 以下を実行してプロジェクトをテストします。

    1. Visual Studio で、ソリューションを構築します。

    2. コマンド ラインで、\bin\debug フォルダに移動し、AppSvcClient.exe を実行します。コマンド ラインでユーザー名とパスワードを渡します。

    コンソール アプリケーションは、ログインしたことを示すメッセージを表示します。

  8. Windows のコマンド ウィンドウに次のコマンドをコピーして、プロファイル サービス プロキシ クラスを生成します。

    svcutil.exe https://localhost:8080/WcfApplicationServices/MyProfileSvcWrap.svc?wsdl /language:"VB" /config:app.config /mergeConfig
    
    svcutil.exe https://localhost:8080/WcfApplicationServices/MyProfileSvcWrap.svc?wsdl /language:"C#" /config:app.config /mergeConfig
    

    /config:app.config オプションは、既定の output.config ファイルの代わりに App.config を構成ファイルとして指定します。/mergeConfig オプションは、この手順で生成される構成情報と、前の手順で生成された App.config ファイル内の情報をマージすることを指定します。

  9. Windows のコマンド ウィンドウに次のコマンドをコピーして、認証サービス プロキシ クラスを生成します。

    svcutil.exe https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"VB" /config:app.config /mergeConfig
    
    svcutil.exe https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"C#" /config:app.config /mergeConfig
    
  10. Windows のコマンド ウィンドウに次のコマンドをコピーして、ロール サービス プロキシ クラスを生成します。

    svcutil.exe https://localhost:8080/WcfApplicationServices/MyRoleSvcWrap.svc?wsdl /language:"VB" /config:app.config /mergeConfig
    
    svcutil.exe https://localhost:8080/WcfApplicationServices/MyRoleSvcWrap.svc?wsdl  /language:"C#" /config:app.config /mergeConfig
    
  11. ソリューション エクスプローラで、コンソール アプリケーションの名前を右クリックし、[追加] をクリックします。次に、[既存の項目] をクリックし、生成したプロキシ クラス ファイルを選択して [追加] をクリックします。

    これらのプロキシ クラスは App.config ファイルと同じフォルダに置かれ、AuthenticationService、ProfileService、および RoleService という名前になります。

  12. Program クラスのコードを次のコードに置き換えます。

    Imports System
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.ServiceModel
    Imports System.ServiceModel.Activation
    Imports System.ServiceModel.Channels
    Imports System.ComponentModel
    Imports System.Web
    Imports System.Net
    
    Module Module1
    
        Class MyServiceTst
    
            Dim _host As String
    
            Public Property Host() As String
                Get
                    Return _host
                End Get
                Set(ByVal value As String)
                    _host = value
                End Set
            End Property
    
            Function GetCookies(ByVal oc As OperationContext) As CookieContainer
                Dim httpResponseProperty As HttpResponseMessageProperty = DirectCast(oc.IncomingMessageProperties(HttpResponseMessageProperty.Name), HttpResponseMessageProperty)
                If (httpResponseProperty.Equals(Nothing) = False) Then
                    Dim cookieContainer As New CookieContainer()
                    Dim header As String = httpResponseProperty.Headers(HttpResponseHeader.SetCookie)
    
                    If header <> Nothing Then
                        cookieContainer.SetCookies(New Uri("http://someuri.tld"), header)
                    End If
                    Return cookieContainer
                End If
                Return Nothing
            End Function
    
            Sub SetCookies(ByVal oc As OperationContext, ByVal cookieContainer As CookieContainer)
                Dim httpRequestProperty = New HttpRequestMessageProperty()
                httpRequestProperty = Nothing
                If oc.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name) Then
                    httpRequestProperty = TryCast(oc.OutgoingMessageProperties(HttpRequestMessageProperty.Name), HttpRequestMessageProperty)
                End If
                If httpRequestProperty Is Nothing Then
                    httpRequestProperty = New HttpRequestMessageProperty()
                    oc.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequestProperty)
                End If
                httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(New Uri("http://someuri.tld")))
            End Sub
    
            Sub GetUserRoles(ByVal cookieContainer As CookieContainer)
                Dim roleSvc As New RoleServiceClient()
    
                Using New OperationContextScope(DirectCast(roleSvc.InnerChannel, IContextChannel))
                    SetCookies(OperationContext.Current, cookieContainer)
                    Dim roles As String() = roleSvc.GetRolesForCurrentUser()
                    If roles.Length = 0 Then
                        Console.WriteLine("User does not belong to any role.")
                    Else
                        Dim userRoles As String = ""
                        Dim i As Integer = 0
                        While i < roles.Length
                            userRoles += roles(i) + " "
                            Global.System.Math.Max(Global.System.Threading.Interlocked.Increment(i), i - 1)
                        End While
                        Console.WriteLine("User's roles: " + userRoles)
    
                    End If
                End Using
            End Sub
    
            Sub GetProfileInfo(ByVal cookieContainer As CookieContainer)
                Dim profileSvc As New ProfileServiceClient()
    
                Using New OperationContextScope(DirectCast(profileSvc.InnerChannel, IContextChannel))
                    SetCookies(OperationContext.Current, cookieContainer)
                    Dim profileData As Dictionary(Of String, Object) = profileSvc.GetPropertiesForCurrentUser(New String() {"FirstName", "LastName", "EmployeeId"}, True)
    
                    Console.WriteLine("FirstName: " + profileData("FirstName"))
                    Console.WriteLine("LastName: " + profileData("LastName"))
                    Console.WriteLine("EmployeeId: " + profileData("EmployeeId"))
                End Using
            End Sub
    
            Public Function strEndPtAddr(ByVal service As String) As String
                Dim endPtAddr As String = "http://" + Host + "/WcfApplicationServices/" + service + ".svc?wsdl"
    
                Return endPtAddr
            End Function
    
            Sub Init(ByVal args As String())
    
                If (args.Length = 3) Then  'The host address was passed in , use that.
                    Host = args(2)
                Else
                    Host = "localhost:8080"  
                End If
    
                Dim username As String = args(0)
                Dim password As String = args(1)
                Dim result As Boolean
                Dim binding As BasicHttpBinding = New BasicHttpBinding()
                Dim endPtAddr As String = strEndPtAddr("MyAuthenSvcWrap")
    
                Console.WriteLine("Attempting to connect as username = " + username + vbNewLine _
                  + "password length = " + password.Length.ToString() + vbNewLine _
                  + " on server " + Host + vbNewLine _
                  + "End point address: " + endPtAddr _
                  )
                ' BasicHttpBinding and endpoint are explicitly passed and ignored
                ' in app.config file.
    
                Dim authService As AuthenticationServiceClient = New AuthenticationServiceClient(binding, _
                                                      New EndpointAddress(endPtAddr))
    
                Dim cookieContainer As CookieContainer = Nothing
                Dim customCredential As String = "Not Used by the default membership provider"
                Dim isPersistent As Boolean = True   ' authentication ticket remains valid across sessions.
    
                Using New OperationContextScope(authService.InnerChannel)
                    Try
                        result = authService.Login(username, password, customCredential, isPersistent)
                        cookieContainer = GetCookies(OperationContext.Current)
                    Catch enf As EndpointNotFoundException
                        Console.WriteLine(enf.Message)
                        Return
                    End Try
    
    
                End Using
    
                If result Then
                    Console.WriteLine("Welcome " + username + ". You have logged in.")
    
                    GetProfileInfo(cookieContainer)
                    GetUserRoles(cookieContainer)
                Else
                    Console.WriteLine("We could not validate your credentials.")
                End If
    
    
            End Sub
        End Class
    
    
    
        Sub Main(ByVal args As String())
    
            If (args.Length < 1) Then
                Console.WriteLine("missing args username password")
                Return
            End If
    
            Dim mst As MyServiceTst = New MyServiceTst()
            mst.Init(args)
    
    
            Console.WriteLine("Enter any key to exit.")
            Console.Read()
    
        End Sub
    
    End Module
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Channels;
    using System.ComponentModel;
    using System.Web;
    using System.Net;
    
    
    class MyServiceTst {
    
        string Host { get; set; }      
    
        CookieContainer GetCookies(OperationContext oc) {
            HttpResponseMessageProperty httpResponseProperty =
                (HttpResponseMessageProperty)oc.IncomingMessageProperties[HttpResponseMessageProperty.Name];
            if (httpResponseProperty != null) {
                CookieContainer cookieContainer = new CookieContainer();
                string header = httpResponseProperty.Headers[HttpResponseHeader.SetCookie];
    
                if (header != null) {
                    cookieContainer.SetCookies(new Uri(@"http://someuri.tld"), header);
                }
                return cookieContainer;
            }
            return null;
        }
    
        void SetCookies(OperationContext oc, CookieContainer cookieContainer) {
    
            HttpRequestMessageProperty httpRequestProperty = null;
            if (oc.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) {
                httpRequestProperty =
                    oc.OutgoingMessageProperties[HttpRequestMessageProperty.Name]
                    as HttpRequestMessageProperty;
            }
    
            if (httpRequestProperty == null) {
                httpRequestProperty = new HttpRequestMessageProperty();
                oc.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name,
                    httpRequestProperty);
            }
            httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie,
                cookieContainer.GetCookieHeader(new Uri(@"http://someuri.tld")));
        }
    
    
        void GetUserRoles(CookieContainer cookieContainer) {
    
            string endPtAddr = strEndPtAddr("MyRoleSvcWrap");
    
            RoleServiceClient roleSvc = new RoleServiceClient(new BasicHttpBinding(),
                 new EndpointAddress(endPtAddr));
    
            using (new OperationContextScope((IContextChannel)roleSvc.InnerChannel)) {
                SetCookies(OperationContext.Current, cookieContainer);
                string[] roles = roleSvc.GetRolesForCurrentUser();
                if (roles.Length == 0) {
                    Console.WriteLine("User does not belong to any role.");
                } else {
                    string userRoles = "";
                    for (int i = 0; i < roles.Length; i++) {
                        userRoles += roles[i] + " ";
                    }
                    Console.WriteLine("User's roles: " + userRoles);
                }
    
            }
        }
    
        void GetProfileInfo(CookieContainer cookieContainer) {
    
            string endPtAddr = strEndPtAddr("MyProfileSvcWrap");
    
            ProfileServiceClient profileSvc = new ProfileServiceClient(new BasicHttpBinding(),
                 new EndpointAddress(endPtAddr));
    
            string[] strProfileProps = new string[] { "FirstName", "LastName", "EmployeeId" };
    
            using (new OperationContextScope((IContextChannel)profileSvc.InnerChannel)) {
                SetCookies(OperationContext.Current, cookieContainer);
                Dictionary<string, object> profileData =
                    profileSvc.GetPropertiesForCurrentUser(strProfileProps, true);
    
                foreach (string sProp in strProfileProps)
                    Console.WriteLine(sProp + ": " + profileData[sProp]);
    
            }
        }
    
        public string strEndPtAddr(string service) {
    
            string endPtAddr = @"http://" + Host + "/WcfApplicationServices/"
                + service + ".svc?wsdl";
    
            return endPtAddr;
        }
    
        public void Init(string[] args) {
    
            if (args.Length == 3)   // The host address was passed in , use that
                Host = args[2];
            else
                Host = "localhost:8080";  
    
            string username = args[0];
            string password = args[1];
            bool result = false;
            BasicHttpBinding binding = new BasicHttpBinding();
            string endPtAddr = strEndPtAddr("MyAuthenSvcWrap");
    
            Console.WriteLine("Attempting to connect as username = " + username
                + "\n password length = " + password.Length.ToString()
                + "\n on server " + Host + "\n"
                + "\n" + endPtAddr
            );
    
            // BasicHttpBinding and endpoint are explicitly passed and ignored
            // in app.config file
    
            AuthenticationServiceClient authService = new AuthenticationServiceClient(binding,
                                                         new EndpointAddress(endPtAddr));
    
            CookieContainer cookieContainer;
            string customCredential = "Not Used by the default membership provider";
            bool isPersistent = true;  // authentication ticket remains valid across sessions.
    
            using (new OperationContextScope(authService.InnerChannel)) {
                try {
                    result = authService.Login(username, password,
                                                 customCredential, isPersistent);
                    cookieContainer = GetCookies(OperationContext.Current);
                } catch (EndpointNotFoundException enfe) {
                    Console.WriteLine(enfe.Message);
                    if (enfe.InnerException != null && enfe.InnerException.Message != null)
                        Console.WriteLine(enfe.InnerException.Message);
                    return;
                }
            }
    
            if (result) {
                Console.WriteLine("Welcome " + username + ". You have logged in.");
    
                GetUserRoles(cookieContainer);
                GetProfileInfo(cookieContainer);
            } else {
                Console.WriteLine("We could not validate your credentials.");
            }
    
        }
    }
    
    class Program {
    
        static void Main(string[] args) {
    
            if (args.Length < 1) {
                Console.WriteLine("missing args username password [host]");
                return;
            }
            MyServiceTst mst = new MyServiceTst();
            mst.Init(args);
    
            Console.WriteLine("Enter any key to exit.");
            // Console.Read();
        }
    
    }
    
    
  13. プロジェクトをビルドします。

アプリケーション サービスへのアクセス

これで、クライアント アプリケーションを実行し、Web サイトの一部として公開したアプリケーション サービスを利用できます。

Windows アプリケーションを実行するには

  1. Windows のコマンド プロンプトで、コンソール アプリケーションのディレクトリに移動します。

  2. 次のコマンドを使用して、チュートリアルの前半で作成したユーザーのうち 1 人のユーザー名とパスワードを入力します。

    AppSvcClient.exe <userName> <password>

    正しい資格情報を入力すると、認証され、ログインしたユーザーに関連付けられているロールとプロファイルの情報を取得できるようになります。

次の手順

このチュートリアルでは、SOAP 形式でメッセージを送受信できるクライアント アプリケーションから ASP.NET アプリケーション サービスにアクセスするための基本的な操作方法を示しました。

その他のアプリケーション サービス機能も試してみてください。次に行う作業の例を示します。

Web サービスの一般的な情報については、次のトピックを学習してください。

  • Web サービス呼び出しを行ったときに発生する処理。詳細については、「XML Web サービスの有効期間の構造」を参照してください。

  • Web サービスを使用する方法。詳細については、「XML Web サービスのシナリオ」を参照してください。

  • ASP.NET アプリケーション サービス。詳細については、「AuthenticationServiceLogin()」を参照してください。

参照

処理手順

方法 : WCF 認証サービスを有効にする

方法 : WCF ロール サービスを有効にする

方法 : WCF プロファイル サービスを有効にする

概念

ASP.NET プロファイル プロパティの定義

ASP.NET アプリケーション サービスの概要