연습: ASP.NET 응용 프로그램 서비스 사용

업데이트: 2007년 11월

ASP.NET 웹 사이트에는 클라이언트 응용 프로그램에서 사용자 인증, 역할 및 프로필 정보에 액세스할 수 있게 해 주는 응용 프로그램 서비스가 있습니다. 서로 다른 언어로 작성되고 서로 다른 운영 체제에서 실행되는 클라이언트 응용 프로그램에서 이 정보에 액세스할 수 있습니다. 단, 이러한 클라이언트가 SOAP 1.1 프로토콜을 통해 통신할 수 있어야 합니다.

이 연습은 다음과 같은 부분으로 나뉘어 있습니다.

  • 1부에서는 응용 프로그램 서비스를 노출하도록 ASP.NET 웹 사이트를 구성하는 방법을 보여 줍니다.

  • 2부에서는 사용자 인증, 역할 및 프로필 정보에 액세스하는 Windows 콘솔 응용 프로그램을 빌드하는 방법을 보여 줍니다. 이 연습에서는 Windows 콘솔 응용 프로그램을 빌드하지만 모든 운영 체제에서 실행되는 클라이언트 응용 프로그램에서 ASP.NET 응용 프로그램 서비스를 사용할 수 있습니다.

사전 요구 사항

이 연습을 완료하려면 다음과 같은 요건을 갖추어야 합니다.

  • Visual Studio 2008. 이 연습에서는 Visual Web Developer Express Edition에서 지원되지 않는 Windows 콘솔 응용 프로그램을 만들므로 Microsoft Visual Web Developer 2005를 사용할 수 없습니다.

  • 컴퓨터에 설치된 Microsoft SQL Server Express Edition

응용 프로그램 서비스 노출

이 단원에서는 네트워크의 클라이언트에서 액세스할 수 있도록 응용 프로그램 서비스를 ASP.NET 웹 사이트의 일부로 노출하는 방법에 대해 설명합니다. 여기서 설명하는 단계는 서버에만 적용됩니다.

참고:

이 연습에서는 파일 시스템 웹 사이트를 사용해야 합니다. 이 연습에서는 IIS 대신 ASP.NET Development Server를 사용하여 예제를 실행해야 합니다.

응용 프로그램 서비스 웹 사이트를 만들려면

  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 Development Server를 시작할 때 임의로 선택된 포트 대신 고정된 포트를 지정합니다. 이 연습에서는 클라이언트 프록시 클래스와 구성 파일을 생성할 때 사용할 수 있는 고정된 포트 번호가 있어야 합니다.

  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>
    
    

    웹 응용 프로그램을 처음으로 실행하면 이 코드에서는 Administrators 및 Friends 역할을 포함하는 Aspnetdb.mdf 로컬 데이터베이스를 만듭니다. 이 데이터베이스는 사용자 자격 증명과 프로필 정보를 저장하는 데 사용됩니다.

  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. New User를 클릭합니다.

    CreateUser.aspx 페이지가 표시됩니다.

  3. 일부 사용자를 만들고 이들을 미리 정의된 역할에 할당합니다. 이렇게 하려면 사용자의 자격 증명을 입력한 다음 Create User를 클릭합니다.

    만든 사용자 이름과 암호를 기억해 둡니다. 사용자의 프로필 정보를 할당하거나 변경할 때 필요합니다.

    사용자를 만든 후 Default.aspx 페이지로 리디렉션됩니다.

  4. Default.aspx 페이지에서 Login을 클릭합니다.

    Login.aspx 페이지가 표시됩니다.

  5. 앞에서 만든 사용자 중 하나의 자격 증명을 사용하여 로그인합니다.

    로그인에 성공하면 Default.aspx 페이지로 리디렉션됩니다.

  6. Profile Information을 클릭합니다.

    Profile.aspx 페이지가 표시됩니다.

  7. 이름, 성 및 ID 번호를 입력하여 로그인한 사용자의 프로필 정보를 입력하거나 업데이트합니다.

  8. Update Profile Data를 클릭합니다.

  9. Read Profile Information을 클릭합니다.

    프로필 속성이 작동하는지 확인할 수 있도록 방금 입력한 정보가 표시됩니다.

  10. Back to default page를 클릭합니다.

사용자와 프로필 정보를 만들었습니다. 이제 클라이언트 응용 프로그램에서 이 정보를 사용할 수 있게 만듭니다.

응용 프로그램 서비스 매핑 및 구성

클라이언트에서 사용자의 자격 증명과 프로필 정보에 액세스할 수 있으려면 먼저 응용 프로그램 서비스를 가리키는 매핑 파일(.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 파일을 저장한 다음 닫습니다.

이제 응용 프로그램 서비스를 노출하도록 웹 응용 프로그램을 구성할 수 있습니다.

응용 프로그램 서비스를 구성하려면

  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 파일을 마우스 오른쪽 단추로 클릭한 다음 브라우저에서 보기를 클릭합니다.

    웹 서비스가 호출되고 서비스에 대한 정보를 제공하는 페이지가 브라우저에 나타납니다. 다음 단계에서 클라이언트 응용 프로그램을 통해 서비스에 액세스할 때 필요하므로 서비스 URL을 기록해 둡니다.

    참고:

    브라우저를 닫지 마십시오. ASP.NET Development Server를 사용할 때 응용 프로그램 서비스가 활성 상태로 유지되려면 브라우저가 열려 있어야 합니다.

웹에서 사용할 수 있도록 웹의 응용 프로그램 서비스 구성을 완료했습니다. 다음 단계에서는 클라이언트 응용 프로그램에서 이러한 서비스를 호출합니다.

응용 프로그램 서비스 사용

이 단원에서는 Windows 콘솔 응용 프로그램 형식의 클라이언트 응용 프로그램을 만들어 응용 프로그램 서비스에 액세스하는 방법을 보여 줍니다. 클라이언트 응용 프로그램에서 SOAP 형식의 메시지를 주고받을 수 있는 경우 클라이언트는 작성된 언어나 실행 중인 운영 체제에 관계없이 응용 프로그램 서비스에 액세스할 수 있습니다.

클라이언트 콘솔 응용 프로그램을 만들려면 다음과 같은 일반적인 단계를 수행합니다.

  • 클라이언트 응용 프로그램을 만듭니다.

  • 응용 프로그램 서비스 프록시 파일과 관련 구성 파일을 생성합니다.

  • 생성한 프록시 및 구성 파일을 클라이언트 응용 프로그램에 추가하고 응용 프로그램을 컴파일합니다.

  • 생성한 프록시를 통해 응용 프로그램 서비스 작업을 호출합니다.

    참고:

    인증 자격 증명과 같은 중요한 사용자 데이터를 전달하는 경우에는 HTTPS 프로토콜을 통해 SSL(Secure Sockets Layer)을 사용합니다. 자세한 내용은 MSDN 웹 사이트의 TranspoHTTP Security and ASP.NET Web Services, 그리고 IIS 웹 사이트의 Configuring Secure Sockets Layer in IIS 7.0을 참조하십시오.

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을 선택한 다음 확인을 클릭합니다.

    그러면 프록시 클래스를 사용하는 데 필요한 클래스를 포함하는 네임스페이스가 프로젝트에 추가됩니다.

응용 프로그램 서비스에 대한 프록시 클래스 및 구성 정보 생성

이제 클라이언트 응용 프로그램에서 ApplicationServicesClient 콘솔 응용 프로그램을 통해 응용 프로그램 서비스에 액세스하는 데 사용할 수 있는 프록시 클래스와 구성 정보를 생성할 수 있습니다. 각 응용 프로그램 서비스에 대해 별도로 프록시 클래스와 구성을 생성합니다.

응용 프로그램 서비스의 프록시 클래스를 생성하려면

  1. Windows 명령줄에서 Service Model Metadata Utility Tool(s) 도구를 포함하는 디렉터리로 변경합니다. 기본 위치는 다음 디렉터리입니다.

    c:\Program Files\Microsoft SDK\Windows\<version>\Bin
    
  2. Svcutil.exe 도구를 사용하여 인증 서비스 프록시 클래스를 생성합니다..

    참고:

    생성하는 구성 파일은 콘솔 응용 프로그램에서 빌드하는 .exe 파일과 이름이 같아야 하지만 config 접미사를 포함해야 합니다. 이 연습에서는 콘솔 응용 프로그램을 만들 때 사용한 이름인 ApplicationServicesClient와 일치하도록 구성 파일의 이름을 ApplicationServicesClient.exe.config로 지정해야 합니다. 이 실행 파일과 구성 파일은 같은 폴더에 있어야 합니다.

    다음 예제에서는 인증, 역할 및 프로필 서비스를 위한 프록시 클래스와 구성 파일을 생성하는 데 사용하는 명령을 보여 줍니다. 여기서 <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 파일을 만들 때 사용한 이름과 일치해야 합니다. 프록시 클래스 파일 이름은 임의로 지정할 수 있습니다. 이 예제에서는 프록시 클래스 파일 이름이 해당하는 .svc 파일의 이름과 일치합니다.

    값 "localhost:8080"은 이 연습에서 웹 사이트를 실행할 때 사용하는 URL과 일치해야 합니다. ASP.NET Development Server에 대해 다른 포트 번호를 사용하거나 동적 포트 할당을 사용하는 경우에는 적절한 값으로 대체합니다. 포트 번호가 변경되는 경우 Svcutil.exe 도구에서 생성한 .config 파일의 내용을 새 포트 번호와 일치하도록 업데이트해야 합니다. 동적 포트 할당을 사용하거나 ASP.NET Development Server의 새 인스턴스를 시작하는 경우가 이에 해당할 수 있습니다.

  3. 솔루션 탐색기에서 콘솔 응용 프로그램의 이름을 마우스 오른쪽 단추로 클릭하고 추가, 기존 항목을 차례로 클릭한 다음 생성한 세 개의 프록시 클래스 파일을 선택하고 추가를 클릭합니다.

  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 클라이언트에서 응용 프로그램 서비스를 사용하는 방법에 대해 알아봅니다. 자세한 내용은 클라이언트 응용 프로그램 서비스 개요를 참조하십시오.

  • WCF(Windows Communication Foundation) 및 클라이언트와 SOAP 형식의 데이터를 교환하는 방법에 대해 알아봅니다. 자세한 내용은 MSDN 웹 사이트에서 XML Web Services Infrastructure를 참조하십시오.

웹 서비스에 대한 일반적인 정보를 알아보려면 다음을 수행할 수 있습니다.

참고 항목

작업

방법: WCF 인증 서비스 활성화

방법: WCF 역할 서비스 활성화

방법: WCF 프로필 서비스 활성화

개념

ASP.NET 응용 프로그램 서비스 개요