연습: AJAX 사용 웹 서비스 만들기 및 사용

업데이트: 2007년 11월

Visual Studio 2008 및 Microsoft Visual Web Developer Express Edition에서는 클라이언트 스크립트에서 액세스할 수 있는 ASP.NET 사용자 지정 웹 서비스(.asmx. 파일)를 만들 수 있습니다. 이 연습에서는 AJAX 사용 웹 서비스를 만들고 클라이언트 스크립트를 사용하여 해당 메서드를 호출할 것입니다.

ASP.NET 웹 서비스를 만들어 이를 클라이언트 스크립트에 노출할 때 ASP.NET은 웹 서비스에 대한 JavaScript 프록시 클래스를 자동으로 만듭니다. 사용자는 JavaScript 프록시 클래스의 해당 메서드를 호출하여 웹 서비스 메서드를 호출할 수 있습니다.

이 연습에서는 다음을 보여 줍니다.

  • Visual Studio 2008 또는 Microsoft Visual Web Developer Express Edition에서 AJAX 사용 웹 서비스를 만드는 방법입니다.

사전 요구 사항

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

  • Visual Studio 2008 또는 Microsoft Visual Web Developer Express Edition

  • 로컬 컴퓨터에 설치되어 있는 Microsoft IIS(인터넷 정보 서비스)

AJAX 사용 웹 서비스 만들기

이 단원에서는 AJAX 사용 웹 서비스를 만드는 방법을 설명합니다.

참고:

이 연습에서는 IIS 웹 사이트를 사용해야 합니다.

AJAX 사용 웹 서비스를 만들려면

  1. Visual Studio 2008 또는 Microsoft Visual Web Developer Express Edition을 엽니다.

  2. 파일 메뉴에서 새 웹 사이트를 클릭합니다.

    새 웹 사이트 대화 상자가 나타납니다.

  3. Visual Studio에 설치되어 있는 템플릿에서 ASP.NET 웹 사이트를 클릭합니다.

  4. 찾아보기를 클릭합니다.

  5. 로컬 IIS를 클릭합니다.

  6. 기본 웹 사이트를 클릭합니다.

  7. 오른쪽 위에서 새 웹 응용 프로그램 만들기 아이콘을 클릭합니다.

    Visual Studio에서 새 IIS 웹 응용 프로그램을 만듭니다.

  8. HelloWorldService라는 이름을 지정합니다.

    참고:

    사용자가 만드는 웹 사이트의 이름은 중요하지 않습니다.

  9. 열기를 클릭합니다.

    맨 오른쪽의 위치 목록에 새 웹 사이트 이름이 표시된 새 웹 사이트 대화 상자가 표시됩니다. 위치에는 프로토콜(http://)과 위치(localhost)가 포함되어 있습니다. 이것은 로컬 IIS 웹 사이트를 사용하고 있음을 나타냅니다.

  10. 언어 목록에서 작업할 프로그래밍 언어를 선택합니다.

  11. 확인을 클릭합니다.

사용자 지정 웹 서비스 작성

이 단원에서는 "Hello World"라는 문자열과 현재 서버 시간을 반환하는 메서드를 제공하는 AJAX 사용 웹 서비스를 작성하는 방법을 설명합니다.

사용자 지정 웹 서비스를 작성하려면

  1. 솔루션 탐색기에서 마우스 오른쪽 단추로 웹 사이트 이름(https://localhost/HelloWorldService)을 클릭한 다음 새 항목 추가를 클릭합니다.

  2. Visual Studio에 설치되어 있는 템플릿에서 웹 서비스를 클릭한 다음 이름 상자에 HelloWorld.asmx를 입력합니다.

  3. 다른 파일에 코드 입력 확인란이 선택되었는지 확인한 다음 추가를 클릭합니다.

    Visual Studio 2008에서 두 개의 파일로 구성된 새 웹 서비스를 만듭니다. HelloWorld.asmx 파일은 웹 서비스 메서드를 호출하기 위해 호출될 수 있는 파일로서 웹 서비스 코드를 가리킵니다. 코드 자체는 App_Code 폴더의 클래스 파일(프로그래밍 언어에 따라 HelloWorld.vb 또는 HelloWorld.cs)에 있습니다. 코드 파일에는 웹 서비스의 템플릿이 포함되어 있습니다.

  4. 클래스에서 기존 코드를 삭제하고 다음 코드로 대체합니다.

    Imports System
    Imports System.Web
    Imports System.Collections
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    
    Namespace Samples.Aspnet
        <WebService([Namespace]:="http://mycompany.org/"), _
        WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1), _
        System.Web.Script.Services.ScriptService()> _
        Public Class HelloWorld
            Inherits System.Web.Services.WebService
    
            Public Sub New()
    
            End Sub 'New
    
    
            'Uncomment the following line if using designed components 
            'InitializeComponent(); 
    
            <WebMethod()> _
            Public Function Greetings() As String
                Dim serverTime As String = _
                    String.Format("Current date and time: {0}.", DateTime.Now)
                Dim greet As String = "Hello World. <br/>" + serverTime
                Return greet
    
            End Function 'Greetings
        End Class 'HelloWorld
    
    End Namespace
    
    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    
    namespace Samples.Aspnet
    {
        [WebService(Namespace="http://mycompany.org")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        // The following attribute allows the service to 
        // be called from script using ASP.NET AJAX.
        [System.Web.Script.Services.ScriptService]
        public class HelloWorld : System.Web.Services.WebService
        {
    
            public HelloWorld()
            {
    
                //Uncomment the following line if using designed components 
                //InitializeComponent(); 
            }
    
            [WebMethod]
            public string Greetings()
            {
                string serverTime =
                    String.Format("Current date and time: {0}.", DateTime.Now);
                string greetings = "Hello World! <br/>" + serverTime;
                return greetings;
            }
    
        }
    }
    

    함수 이름 앞에는 함수 선언의 일부로 WebMethodAttribute 특성이 옵니다. 또한 HelloWorld 클래스는 ScriptServiceAttribute 특성으로 한정됩니다.

    이 특성을 사용하면 AJAX 사용 ASP.NET 웹 페이지의 스크립트에서 웹 서비스를 호출할 수 있습니다.

  5. 파일을 저장하고 닫습니다.

  6. HelloWorld.asmx 파일을 열고 다음 지시문을 추가합니다.

    <%@ WebService Language="VB" CodeBehind="~/App_Code/HelloWorld.vb" Class="Samples.Aspnet.HelloWorld" %>
    
    <%@ WebService Language="C#" CodeBehind="~/App_Code/HelloWorld.cs" Class="Samples.Aspnet.HelloWorld" %>
    
  7. 파일을 저장하고 닫습니다.

이제 브라우저에서 웹 서비스를 테스트할 수 있습니다. 이 테스트는 웹 서비스 메서드를 호출할 때 스크립트를 사용하지 않습니다. 단지 웹 서비스가 제대로 작동하는지 확인하기 위한 것입니다.

웹 서비스를 테스트하려면

  1. 브라우저를 열고 https://localhost/HelloWorldService/HelloWorld.asmx URL을 입력합니다.

    웹 서비스가 호출되고 이 웹 서비스에 의해 노출되는 메서드를 보여 주는 페이지가 브라우저에 나타납니다.

  2. Greetings를 클릭합니다. 호출 단추가 있는 페이지가 나타납니다.

  3. 호출 단추를 클릭하여 메서드를 호출하고 XML 형식의 반환 값을 살펴봅니다.

  4. 브라우저를 닫습니다.

AJAX 사용 웹 서비스 만들기가 완료되었습니다.

웹 서비스 사용

다음 단계에서는 클라이언트 스크립트에서 웹 서비스를 호출합니다.

클라이언트 스크립트에서 웹 서비스를 호출하려면

  1. 솔루션 탐색기에서 마우스 오른쪽 단추로 웹 사이트 이름(https://localhost/HelloWorldService)을 클릭한 다음 새 항목 추가를 클릭합니다.

  2. Visual Studio에 설치되어 있는 템플릿에서 JScript 파일을 클릭한 다음 이름 상자에 HelloWorld.js를 입력합니다.

  3. 확인을 클릭합니다.

  4. 다음 코드를 스크립트 파일에 추가합니다.

    var helloWorldProxy;
    
    // Initializes global and proxy default variables.
    function pageLoad()
    {
        // Instantiate the service proxy.
        helloWorldProxy = new Samples.Aspnet.HelloWorld();
    
        // Set the default call back functions.
        helloWorldProxy.set_defaultSucceededCallback(SucceededCallback);
        helloWorldProxy.set_defaultFailedCallback(FailedCallback);
    }
    
    
    // Processes the button click and calls
    // the service Greetings method.  
    function OnClickGreetings()
    {
        var greetings = helloWorldProxy.Greetings();
    }
    
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result)
    {
        var RsltElem = document.getElementById("Results");
        RsltElem.innerHTML = result;
    }
    
    // Callback function invoked when a call to 
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) 
    {
        if(error !== null) 
        {
            var RsltElem = document.getElementById("Results");
    
            RsltElem.innerHTML = "An error occurred: " + 
                error.get_message();
        }
    }
    
    if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    이 클라이언트 스크립트는 HelloWorld 서비스 메서드를 호출하기 위해 Default.aspx 페이지에서 사용합니다.

  5. Visual Studio 2008에서 Default.aspx 페이지를 엽니다.

  6. 페이지에서 기존 태그를 삭제하고 다음 코드로 대체합니다.

    <%@ Page Language="VB" AutoEventWireup="false" %>
    
    <!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" >
            <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        color: #000000;
                        padding-top: 72px;
                        text-align: center }
    
                .text { font: 8pt Trebuchet MS }
            </style>
    
            <title>Using AJAX Enabled ASP.NET Service</title>
    
        </head>
    
        <body>
            <form id="Form1" >
                <asp:ScriptManager  ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                    </Services>
                    <Scripts>
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    </Scripts>
                </asp:ScriptManager>
                <div>
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
    
                    <table>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                            <td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                            </td>
                        </tr>
                    </table>
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    
    <%@ Page Language="C#" %>
    
    <!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" >
            <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        color: #000000;
                        padding-top: 72px;
                        text-align: center }
    
                .text { font: 8pt Trebuchet MS }
            </style>
    
            <title>Using AJAX Enabled ASP.NET Service</title>
    
        </head>
    
        <body>
            <form id="Form1" >
                <asp:ScriptManager  ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                    </Services>
                    <Scripts>
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    </Scripts>
                </asp:ScriptManager>
                <div>
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
    
                    <table>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                            <td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                            </td>
                        </tr>
                    </table>
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    

    페이지에 ScriptManager 컨트롤이 포함되어 있습니다. Services 단원에 나오는 ServiceReference 요소의 path 특성은 앞에서 만든 HelloWorld 서비스를 참조합니다. Script 단원에 나오는 ServiceReference 요소의 path 특성은 HelloWorld.js 스크립트를 참조합니다.

  7. 브라우저를 열고 다음 URL을 입력합니다.

    http://<localhost>/HelloWorldService/Default.aspx

  8. 표시된 페이지에서 Greetings 단추를 클릭합니다.

    이는 인사 메시지와 현재 서버 날짜 및 시간을 반환하는 웹 서비스에 대한 호출을 생성합니다.

다음 단계

이 연습에서는 웹 서비스를 만들고 이를 클라이언트 스크립트의 웹 페이지에서 호출하는 기본 원칙을 설명했습니다. 더 복잡한 다른 웹 서비스 기능을 사용해 보려는 경우 다음과 같은 제안을 따르는 것이 좋습니다.

참고 항목

개념

웹 서비스를 클라이언트 스크립트로 노출

클라이언트 스크립트에서 웹 서비스 호출

ASP.NET AJAX의 웹 서비스 사용