共用方式為


逐步解說:使用 ASP.NET 應用程式服務

更新:2007 年 11 月

ASP.NET 會在 Web 上提供應用程式服務,用戶端應用程式可使用該服務存取使用者驗證、角色和設定檔資訊。 以其他語言撰寫而成且在不同作業系統上執行的用戶端應用程式,都可以存取這項資訊。唯一的要求是,這些用戶端要能夠透過 SOAP 1.1 通訊協定進行通訊。

本逐步解說分為下列部分:

  • 第 1 部分示範如何設定 ASP.NET 網站,以公開應用程式服務。

  • 第 2 部分示範如何建置可存取使用者驗證、角色及設定檔資訊的 Windows 主控台應用程式。在本逐步解說中,您將會建置 Windows 主控台應用程式,但 ASP.NET 應用程式服務可提供給在任何作業系統上執行的用戶端應用程式。

必要條件

若要完成這個逐步解說,您必須要有:

  • Visual Studio 2008。您無法使用 Microsoft Visual Web Developer 2005 來執行本逐步解說,因為 Visual Web Developer Express 版中不支援您要建立的 Windows 主控台應用程式。

  • Microsoft SQL Server Express 版已安裝在您的電腦上。

公開應用程式服務

本節說明如何公開應用程式服務做為 ASP.NET 網站的一部分,以供網路上的任何用戶端存取。本文所描述的步驟僅適用於該伺服器。

注意事項:

在此逐步解說中,您必須使用檔案系統網站。此逐步解說必須使用 ASP.NET 程式開發伺服器,而非使用 IIS 執行範例。

若要建立應用程式服務網站

  1. 開啟 Visual Studio 2008。

  2. 按一下 [檔案] 功能表上的 [新網站]。

    [新網站] 對話方塊隨即出現。

  3. 請在 [Visual Studio 安裝的範本] 下方,選取 [ASP.NET 網站]。

  4. 在 [位置] 清單中,選取 [檔案系統]。

  5. 在 [資料夾] 文字方塊中,輸入下列位置:

    C:\WcfApplicationServices

  6. 按一下 [確定]。

    Visual Studio 會建立新的 ASP.NET 網站,並開啟 Default.aspx 頁面。

  7. 在 [方案總管] 中,按一下網站的名稱。

  8. 在 [屬性] 視窗中,將 [使用動態通訊埠] 設定為 [False]。

    這麼做會指示 Visual Studio 指定一個固定的通訊埠,而不是在啟動 ASP.NET 程式開發伺服器時隨機選取通訊埠。在本逐步解說中,您必須有固定的通訊埠編號,在產生用戶端 Proxy 類別和組態檔時可使用。

  9. 將 [通訊埠編號] 設定為 8080。

    注意事項:

    您可以使用任何可用的通訊埠。如果您使用其他通訊埠,請記下通訊埠的編號,以便取代本逐步解說稍後的 8080 編號。

ASP.NET 成員資格、角色及設定檔資訊都儲存在資料庫中。有需要時,這個資料庫就會自動建立。在下一個程序中,您將建立應用程式的使用者和角色,此應用程式會自動建立資料庫。

若要建立使用者及角色資訊

  1. 將 Global.asax 檔案加入至網站中,並加入下列程式碼。

    <%@ Application Language="VB" %>
    
    <script >
    
        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 >
    
        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.aspx 頁面,並加入下面的標記。

    <%@ 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" >
        <title>Application Services Home Page</title>
    </head>
    <body>
        <form id="form1" >
        <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" />
            </p>
    
            <table border="1">
                <tr>
                    <td align="left">Login to change profile</td>
                    <td align="left"><asp:LoginStatus ID="LoginStatus1"  /></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 >
        <title>Application Services Home Page</title>
    </head>
    <body>
        <form id="form1" >
        <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" />
            </p>
    
            <table border="1">
                <tr>
                    <td align="left">Login to change profile</td>
                    <td align="left"><asp:LoginStatus ID="LoginStatus1"  /></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 檔案,或程式碼後置檔案。

    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 的頁面,並在其中加入下列標記:

    <%@ 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 >
        <title>Login Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <asp:Login ID="Login1"    />
        </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 >
        <title>Login Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <asp:Login ID="Login1"   />
        </div>
        </form>
    </body>
    </html>
    
  5. 加入名為 Profile.aspx 的頁面,並確定已選取 [將程式碼置於個別檔案中]。

  6. 將下列標記加入至 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" >
        <title>Profile Page</title>
    </head>
    <body>
        <form id="form1" >
        <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"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">User Roles</td>
                    <td align="left">
                        <asp:Label ID="Label2"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">First Name</td>
                    <td>
                        <asp:Label ID="Label3"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td>    
                        <asp:Label ID="Label4"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td>    
                        <asp:Label ID="Label5"  Text="Label"/>
                    </td>
                </tr>
    
            </table>
            <asp:Button ID="Button2"  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" /></td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td align="left"><asp:TextBox ID="TextBox2" /></td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td align="left"><asp:TextBox ID="TextBox3" /></td>
                </tr>
    
            </table>
    
            <asp:Button ID="Button1"  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" >
        <title>Profile Page</title>
    </head>
    <body>
        <form id="form1" >
        <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"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">User Roles</td>
                    <td align="left">
                        <asp:Label ID="Label2"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">First Name</td>
                    <td>
                        <asp:Label ID="Label3"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td>    
                        <asp:Label ID="Label4"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td>    
                        <asp:Label ID="Label5"  Text="Label"/>
                    </td>
                </tr>
    
            </table>
            <asp:Button ID="Button2"  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" /></td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td align="left"><asp:TextBox ID="TextBox2" /></td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td align="left"><asp:TextBox ID="TextBox3" /></td>
                </tr>
    
            </table>
    
            <asp:Button ID="Button1"  onclick="Button1_Click" 
            Text="Update Profile Data" />
    
        </div>
        </form>
    </body>
    </html>
    
  7. 將下列程式碼加入至 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;
            }
        }
    }
    

    這個頁面可讓您取得及變更使用者設定檔資訊。

  8. 加入名為 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 >
        <title>Add New User</title>
    </head>
    <body>
        <form id="form1" >
        <div>
    
            <h2>Add New User</h2>
    
            <a href="Default.aspx">back to default page</a>
    
            <asp:CreateUserWizard ID="CreateUserWizard1" 
              OnCreatedUser="On_CreatedUser">
                <wizardsteps>
                    <asp:CreateUserWizardStep ID="CreateUserWizardStep1"   />
                    <asp:CompleteWizardStep ID="CompleteWizardStep1"   />
                </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"  />
    
        </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" >
        <title>Add New User</title>
    </head>
    <body>
        <form id="form1" >
        <div>
    
            <h2>Add New User</h2>
    
            <a href="Default.aspx">back to default page</a>
    
            <asp:CreateUserWizard ID="CreateUserWizard1" 
              OnCreatedUser="On_CreatedUser">
                <wizardsteps>
                    <asp:CreateUserWizardStep ID="CreateUserWizardStep1"   />
                    <asp:CompleteWizardStep ID="CompleteWizardStep1"   />
                </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"  />
    
        </div>
        </form>
    </body>
    </html>
    
  9. 將下列程式碼加入至 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.config 檔案中的組態設定。

若要設定驗證、角色和設定檔屬性

  1. 開啟網站的 Web.config 檔案。

  2. 在 system.web 群組中,透過 authentication 項目啟用表單驗證,如下面的範例所示:

    <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>
    

    這個組態項目會定義三個設定檔屬性,名稱分別為 FirstName、LastName 和 EmployeeId。

您現在可以建立稍後登入時要用的使用者資訊。

若要建立使用者及指派設定檔資訊

  1. 在瀏覽器的輸入位址方塊中輸入下列 URL,即可顯示 Default.aspx 頁面:

    https://localhost:8080/WcfApplicationServices/Default.aspx

  2. 按一下 [新增使用者]。

    CreateUser.aspx 頁面隨即顯示。

  3. 建立一些使用者並將他們指派給預先定義的角色。若要這麼做,請輸入使用者的認證,然後按一下 [建立使用者]。

    請記得您所建立的使用者名稱及密碼。您需要這些資訊才能指派或變更使用者設定檔資訊。

    建立使用者後,會重新導向至 Default.aspx 頁面。

  4. 在 Default.aspx 頁面中,按一下 [登入]。

    Login.aspx 頁面隨即顯示。

  5. 使用您稍早所建立的其中一個使用者認證來登入。

    如果您順利登入,就會重新導向至 Default.aspx 頁面。

  6. 按一下 [設定檔資訊]。

    Profile.aspx 頁面隨即顯示。

  7. 輸入名字、姓氏及身分識別碼,以輸入或更新登入之使用者的設定檔資訊。

  8. 按一下 [更新設定檔資料]。

  9. 按一下 [讀取設定檔資訊]。

    這麼做會顯示您剛才輸入的資訊,以確認設定檔屬性可正常運作。

  10. 按一下 [返回預設頁面]。

您已完成建立使用者及設定檔資訊。您現在要讓用戶端應用程式能夠使用這項資訊。

對應和設定應用程式服務

您必須建立指向應用程式服務的對應檔案 (.svc),才能夠從用戶端存取使用者認證及設定檔資訊。這麼做可以讓在任何可傳送及接收 SOAP 格式訊息的平台上執行之應用程式使用這項服務。您也必須設定網站,在網路上公開應用程式服務。

若要建立應用程式服務對應檔

  1. 將 WCF 服務檔案 (.svc) 加入至網站,並將其命名為 AuthenticationService.svc。

  2. 開啟 AuthenticationService.svc 檔案、刪除檔案中的任何內容,然後將下列指示詞複製到檔案中,這個指示詞會建立 AuthenticationService 類別的參考:

    <%@ ServiceHost Service="System.Web.ApplicationServices.AuthenticationService" ServiceHosting="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Service="System.Web.ApplicationServices.AuthenticationService" ServiceHosting="System.Web.ApplicationServices.ApplicationServicesHostFactory" %> 
    
  3. 將另一個 WCF 服務檔案 (.svc) 加入至網站,並將其命名為 RoleService.svc。

  4. 開啟 RoleService.svc 檔案,並以下列指示詞取代其內容,這個指示詞會建立 RoleService 類別的參考:

    <%@ ServiceHost Service="System.Web.ApplicationServices.RoleService" ServiceHosting="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Service="System.Web.ApplicationServices.RoleService" ServiceHosting="System.Web.ApplicationServices.ApplicationServicesHostFactory" %> 
    
  5. 將另一個 WCF 服務檔案 (.svc) 加入至網站,並將其命名為 ProfileService.svc。

  6. 開啟 ProfileService.svc 檔案並以下列指示詞取代其內容,這個指示詞會建立 ProfileService 類別的參考:

    <%@ ServiceHost Service="System.Web.ApplicationServices.ProfileService" ServiceHosting="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Service="System.Web.ApplicationServices.ProfileService" ServiceHosting="System.Web.ApplicationServices.ApplicationServicesHostFactory" %> 
    
  7. 儲存並關閉所有 .svc 檔案。

您現在可以設定 Web 應用程式以公開應用程式服務。

若要設定應用程式服務

  1. 開啟或切換至網站的 Web.config 檔案,並在 scripting 項目的 system.web.extensions 區段中,透過 webServices 區段啟用應用程式服務。

    下列範例顯示組態區段的樣子。

      <system.web.extensions>
    
            <scripting>
                <webServices>
                    <authenticationService enabled="true"/>
                    <profileService
                        enabled="true"
                        readAccessProperties="FirstName,LastName,EmployeeId"/>
                    <roleService enabled="true"/>
                </webServices>
            </scripting>
    
        </system.web.extensions>
    
  2. 在 system.serviceModel 群組中,設定應用程式服務,讓用戶端應用程式能夠使用 SOAP 通訊協定來存取這些服務。設定服務 endpoint 項目,如下列範例所示:

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

您現在可以啟動網站,以公開 Windows 用戶端應用程式會使用的應用程式服務。這麼做也可讓您確認應用程式服務基礎架構是否正常運作。

若要啟動網站以公開應用程式服務

  • 在 [方案總管] 中,以滑鼠右鍵按一下 AuthenticationService.svc 檔案,然後按一下 [在瀏覽器中檢視]。

    這麼做會叫用 Web 服務,瀏覽器中會顯示一個頁面,提供您有關服務的資訊。請記下服務 URL,因為您在下一步需要這項資訊,才能從用戶端應用程式存取該服務。

    注意事項:

    不要關閉瀏覽器。當您使用 ASP.NET 程式開發伺服器時,瀏覽器必須維持開啟,應用程式服務才能維持作用。

您已完成了設定 Web 上的應用程式服務,服務現在可以在 Web 上使用。下一步是從用戶端應用程式叫用這些服務。

使用應用程式服務

這個區段示範如何以 Windows 主控台應用程式的格式建立用戶端應用程式,以存取應用程式服務。以任何語言撰寫而成且在任何作業系統上執行的用戶端,都可以存取這個應用程式服務,只要用戶端應用程式可以傳送及接收 SOAP 格式的訊息即可。

若要建立用戶端主控台應用程式,您要遵循這些一般步驟:

  • 建立用戶端應用程式。

  • 產生應用程式服務 Proxy 檔案,以及相關的組態檔。

  • 將產生的 Proxy 及組態檔加入至用戶端應用程式,並編譯應用程式。

  • 透過產生的 Proxy 呼叫應用程式服務作業。

    注意事項:

    如果您傳送的是敏感的使用者資料,例如驗證認證,請使用 Secure Sockets Layer (SSL,使用 HTTPS 通訊協定)。如需詳細資訊,請參閱 MSDN 網站上的傳輸安全性 (英文) 及 HTTP 安全性與 ASP.NET Web 服務 (英文),以及 IIS 網站上的 在 IIS 7.0 中設定 Secure Sockets Layer (英文)。

若要建立 Windows 主控台應用程式

  1. 在 Visual Studio 中,按一下 [檔案] 功能表上的 [新增],然後按一下 [新增專案]。

  2. 選取您慣用的語言,然後選取 [Visual Studio 安裝的範本] 之下的 [主控台應用程式]。

  3. 將應用程式命名為 ApplicationServicesClient、輸入應用程式的位置,然後按一下 [確定]。

    Visual Studio 會將專案加入至目前的方案中,然後開啟預設的類別檔。

  4. 以下列程式碼取代檔案中的預設程式碼:

    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;
    
    namespace ApplicationServicesClientConsole
    {
        class Program
        {
            static 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;
            }
    
            static 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")));
            }
    
    
            static void GetUserRoles(CookieContainer cookieContainer)
            {
                RoleServiceClient roleSvc = new RoleServiceClient();
    
                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);
                    }
    
                }
            }
    
            static void GetProfileInfo(CookieContainer cookieContainer)
            {
                ProfileServiceClient profileSvc = new ProfileServiceClient();
    
                using (new OperationContextScope((IContextChannel)profileSvc.InnerChannel))
                {
                    SetCookies(OperationContext.Current, cookieContainer);
                    Dictionary<string, object> profileData =
                        profileSvc.GetPropertiesForCurrentUser(
                            new string[] { "FirstName", "LastName", "EmployeeId"},
                            true);
    
                    Console.WriteLine("FirstName: " + profileData["FirstName"]);
                    Console.WriteLine("LastName: " + profileData["LastName"]);
                    Console.WriteLine("EmployeeId: " + profileData["EmployeeId"]);
                }
            }
    
            static void Main(string[] args)
            {
                string username;
                string password;
                bool result = false;
    
                Console.Write("Enter user name: ");
                username = Console.ReadLine();
    
                Console.Write("Enter password: ");
                password = Console.ReadLine();
    
                BasicHttpBinding binding = new BasicHttpBinding();
    
                string LoginUri =
                    @"https://localhost:8080/WcfApplicationServices/AuthenticationService.svc?wsdl";
    
                AuthenticationServiceClient authService =
                new AuthenticationServiceClient(binding,
                    new EndpointAddress(LoginUri));
    
                CookieContainer cookieContainer;
    
                using (new OperationContextScope(authService.InnerChannel))
                {
                    result = authService.Login(username, password,
                                "User Context: Console Test.", true);
                    cookieContainer = GetCookies(OperationContext.Current);
                }
    
                if (result)
                {
                    Console.WriteLine("Welcome " + username + ". You have logged in.");
    
                    GetUserRoles(cookieContainer);
                    GetProfileInfo(cookieContainer);
                }
                else
                {
                    Console.WriteLine("We could not validate your credentials.");
                }
    
                Console.WriteLine("Enter any key to exit.");
                Console.Read();
            }
    
        }
    }
    

    程式碼可讓您輸入使用者名稱與密碼。您必須使用在本逐步解說中稍早所建立之使用者及密碼的值。

  5. 關閉檔案。

  6. 以滑鼠右鍵按一下主控台應用程式的名稱,然後按一下 [加入參考]。

  7. 在 [加入參考] 對話方塊中,按一下 [.NET] 索引標籤,選取 [System.ServiceModel] 及 [System.Runtime.Serialization],然後按一下 [確定]。

    這麼做會將命名空間加入至專案中,此專案包含使用 Proxy 類別時所需要的類別。

產生應用程式服務的 Proxy 類別及組態資訊

您現在可以產生 Proxy 類別及組態資訊,讓主控台應用程式存取 ApplicationServicesClient 主控台應用程式中的應用程式服務。您要為每一個應用程式服務分別產生一個 Proxy 類別及組態。

若要產生應用程式服務的 Proxy 類別

  1. 在 Windows 命令列,切換至內含 ServiceModel 中繼資料公用程式工具 (Svcutil.exe) (英文) 的目錄。預設位置是下列目錄:

    c:\Program Files\Microsoft SDK\Windows\<version>\Bin
    
  2. 使用 Svcutil.exe 工具產生驗證服務 Proxy 類別。

    注意事項:

    您所產生的組態檔必須和您使用主控台應用程式所建置的 .exe 檔案同名,但字尾要加上 config。在這個逐步解說中,.configuration 檔案必須命名為 ApplicationServicesClient.exe.config,才會和您用來建立主控台應用程式的 ApplicationServicesClient 名稱相符。可執行檔和組態檔必須位於同一資料夾中。

    下列範例示範的命令,您可用來產生 Proxy 類別,以及用於驗證、角色及設定檔服務的組態檔。以適當的磁碟機代號取代 <drive>。

    // Generating AuthenticationService proxy
    svcutil "https://localhost:8080/ApplicationServices_VB/AuthenticationService.svc?wsdl" /language:"VB" /out:"<drive>:\AppServicesProxies\AuthenticationService.vb" /config:"<drive>:\AppServicesProxies\ApplicationServicesClient_VB.exe.config"
    
    // Generating RoleService proxy
    svcutil "https://localhost:8080/ApplicationServices_VB/RoleService.svc?wsdl" /language:"VB" /out:"<drive>:\AppServicesProxies\RoleService.vb" /config:"<drive>:\AppServicesProxies\ApplicationServicesClient_VB.exe.config" /mergeConfig 
    
    // Generating ProfileService proxy
    svcutil "https://localhost:8080/ApplicationServices_VB/ProfileService.svc?wsdl" /language:"VB" /out:"<drive>:\AppServicesProxies\ProfileService.vb" /config:"<drive>:\AppServicesProxies\ApplicationServicesClient_VB.exe.config" /mergeConfig 
    
    
    // Generating AuthenticationService proxy
    svcutil "https://localhost:8080/ApplicationServices/AuthenticationService.svc?wsdl" /Language:"C#" /out:"<drive>:AppServicesProxies\AuthenticationService.cs" /config:"<drive>:\AppServicesProxies\ApplicationServicesClient.exe.config"
    
    // Generating RoleService proxy
    svcutil "https://localhost:8080/ApplicationServices/RoleService.svc?wsdl" /Language:"C#" /out:"<drive>:\AppServicesProxies\RoleService.cs" /config:"<drive>:\AppServicesProxies\ApplicationServicesClient.exe.config" /mergeConfig 
    
    // Generating ProfileService proxy
    svcutil "https://localhost:8080/ApplicationServices/ProfileService.svc?wsdl" /Language:"C#" /out:"<drive>:\AppServicesProxies\ProfileService.cs" /config:"<drive>:\AppServicesProxies\ApplicationServicesClient.exe.config" /mergeConfig 
    
    
    

    命令中的 .svc 檔案名稱,必須與您在本逐步解說中稍早用來建立 .svc 檔案的名稱相同。Proxy 類別檔案名稱是強制的,在這個範例中,Proxy 類別名稱與對應的 .svc 檔案名稱相符。

    值 "localhost:8080" 必須與您從這個逐步解說中執行網站時所使用的 URL 相符。如果您的 ASP.NET 程式開發伺服器使用其他通訊埠編號,或如果您使用動態通訊埠指派,請以適當的值取代。如果通訊埠編號變更,您必須更新 Svcutil.exe 工具所產生的 .config 檔案,以配合新的通訊埠編號。如果您使用動態通訊埠指派,並啟動 ASP.NET 程式開發伺服器的新執行個體,可能可以這麼做。

  3. 在 [方案總管] 中,以滑鼠右鍵按一下主控台應用程式,按一下 [加入],再按一下[現有項目],選取您所產生的三個 Proxy 類別檔,然後按一下 [加入]。

  4. 建置主控台應用程式專案。

    專案輸出為 ApplicationServicesClient.exe 可執行檔。

  5. 將您產生的 ApplicationServicesClient.exe.config 檔案加入至資料夾中,此資料夾內含主控台應用程式可執行檔。

    根據預設,該資料夾為下列資料夾,其中 <folder> 是您建立主控台應用程式之資料夾的名稱。

    <folder>\bin\Debug
    

存取應用程式服務

您現在可以執行用戶端應用程式,並使用公開為網站之一部分的應用程式服務。

若要執行 Windows 應用程式

  1. 在 Windows 命令提示字元中,切換至您用來儲存主控台應用程式及其相關組態檔的目錄 (如果您使用預設值,則位置為 <folder>\bin\Debug)。

  2. 輸入下列命令:

    ApplicationServicesClient.exe

  3. 當應用程式提示時,請輸入您在本逐步解說中稍早所建立的其中一個使用者名稱及密碼。

    如果您輸入正確的認證,就會通過驗證而且能夠取得與登入的使用者相關的角色及設定檔資訊。

後續步驟

本逐步解說已說明從可傳送及接收 SOAP 格式訊息的用戶端應用程式,存取 ASP.NET 應用程式服務的基本原則。

您可能會想要試驗其他應用程式服務功能。建議您進一步探索下列各項:

  • 進一步了解 .NET Framework 用戶端使用應用程式服務的詳細資訊。如需詳細資訊,請參閱用戶端應用程式服務概觀

  • 進一步了解 Windows Communication Foundation (WCF),以及與用戶端進行 SOAP 格式的資料交換。如需詳細資訊,請參閱 MSDN 網站上的 XML Web Service 基礎架構 (英文)。

如需 Web 服務的一般資訊,您可能需要執行下列動作:

請參閱

工作

HOW TO:啟用 WCF 驗證服務

HOW TO:啟用 WCF 角色服務

HOW TO:啟用 WCF 設定檔服務

概念

ASP.NET 應用程式服務概觀