Share via


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

업데이트: 2007년 11월

ASP.NET의 AJAX 기능을 사용하면 브라우저에서 클라이언트 스크립트를 사용하여 ASP.NET 웹 서비스(.asmx 파일)를 호출할 수 있습니다. 이렇게 하면 웹 응용 프로그램에 대한 사용자 경험이 향상됩니다. 브라우저와 웹 서버 간에 데이터만 전송되기 때문에 페이지에서 포스트백 및 전체 페이지에 대한 새로 고침 없이 서버 기반 메서드를 호출할 수 있습니다.

이 항목에서는 브라우저에서 실행되는 JavaScript에서 웹 서비스를 사용할 수 있는 방법에 대해 설명합니다.

ASP.NET에서는 웹 서비스의 JavaScript 프록시 클래스를 자동으로 만듭니다. 프록시 클래스는 Sys.Net.WebServiceProxy 클래스에서 파생됩니다. 사용자는 JavaScript 프록시 클래스의 해당 메서드를 호출하여 웹 서비스 메서드를 호출할 수 있습니다. 자세한 내용은 클라이언트 스크립트에서 웹 서비스 호출을 참조하십시오.

스크립트에서 액세스할 수 있도록 웹 서비스 만들기

스크립트에서 웹 서비스에 액세스하려면 웹 서비스가 웹 서비스 클래스가 ScriptServiceAttribute 특성을 사용하여 한정된 .asmx 웹 서비스이어야 합니다. 스크립트에서 호출하는 각 메서드는 WebMethodAttribute 특성을 사용하여 한정되어야 합니다.

다음 예제에서는 웹 서비스 코드의 이러한 특성을 보여 줍니다.

[ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string EchoInput(String input)
    {
        // Method code goes here.
    }
}

<ScriptService> _
Public Class SimpleWebService
        Inherits System.Web.Services.WebService
    <WebMethod> _
    Public Function EchoInput(ByVal input As String) As String
        ' Method code goes here.
    End Function
End Class

스크립트에서 웹 서비스를 호출할 수 있도록 하려면 응용 프로그램의 Web.config 파일에 ScriptHandlerFactory HTTP 처리기를 등록해야 합니다. 이 처리기에서 스크립트에서 .asmx 웹 서비스로의 호출을 처리합니다. 다음 예제에서는 처리기를 추가하기 위한 Web.config 요소를 보여 줍니다.

참고:

이러한 구성 설정은 Microsoft Visual Studio 2005에서 만든 모든 새 AJAX 사용 웹 사이트를 위한 Web.config 파일 템플릿의 일부입니다.

<system.web>
  <httpHandlers>
    <remove verb="*" path="*.asmx"/> 
    <add verb="*" path="*.asmx" 
      type="System.Web.Script.Services.ScriptHandlerFactory"
       validate="false"/>
  </httpHandlers>
<system.web>

ASP.NET AJAX 스크립트에서 발생하지 않는 웹 서비스 호출의 경우 ScriptHandlerFactory 처리기에서 해당 호출을 JSON 대신에 SOAP 형식을 사용하는 기본 처리기에 위임합니다. 위임은 자동 수행되기 때문에 웹 서비스에 대해 SOAP 프로토콜을 사용하지 않도록 설정하려는 경우가 아니면 아무런 조치도 취할 필요가 없습니다. 이 경우 사용자는 Web.config 파일에 다음 구성 설정을 입력해야 합니다.

<system.web>
  <webServices>    <protocols>      <clear/>    </protocols>  </webServices>
</system.web>

웹 서비스를 ASP.NET 웹 페이지의 클라이언트 스크립트로 노출

ASP.NET 웹 페이지의 클라이언트 스트립트에서.asmx 웹 서비스를 호출할 수 있도록 하려면 ScriptManager 컨트롤을 페이지에 추가해야 합니다. asp:ServiceReference 자식 요소를 ScriptManager 컨트롤에 추가한 다음 서버 참조 path 특성을 웹 서비스의 URL로 설정하여 웹 서비스를 참조합니다. ServiceReference 개체에서는 클라이언트 스크립트에서 지정한 웹 서비스를 호출하기 위해 JavaScript 프록시 클래스를 생성하도록 ASP.NET에게 지시합니다.

다음 예제에서는 ASP.NET 웹 페이지의 스크립트에서 SimpleWebService.asmx라는 웹 서비스를 호출할 수 있도록 지정하는 방법을 보여 줍니다.

<asp:ScriptManager  ID="scriptManager">
  <Services>
    <asp:ServiceReference
       path="~/WebServices/SimpleWebService.asmx" />
  </Services>
</asp:ScriptManager>

ServiceReference 개체는 페이지와 동일한 도메인의 웹 서비스만 참조할 수 있습니다. 웹 서비스 경로는 상대, 응용 프로그램 상대, 도메인 상대 또는 절대 경로일 수 있습니다. 절대 경로의 경우 경로는 동일한 도메인 내에 있어야 합니다.

ScriptManager 컨트롤이 포함된 페이지를 렌더링하면 해당 페이지에서 SimpleWebService.asmx 웹 서비스용 JavaScript 프록시 클래스를 만듭니다. 해당 프록시 클래스에는 SimpleWebService.asmx 서비스의 웹 메서드에 해당하는 메서드가 있습니다. 또한 페이지에는 웹 서비스 메서드의 입력 매개 변수 또는 반환 값으로 사용되는 서버 데이터 형식에 해당하는 JavaScript 프록시 클래스가 포함되어 있습니다. 이러한 클래스를 사용하면 이러한 매개 변수를 초기화하는 클라이언트 스크립트를 작성한 다음 메서드 호출에 전달할 수 있습니다.

ServiceReference 개체의 InlineScript 속성은 JavaScript 프록시 클래스를 페이지에 포함하는 방법을 지정합니다. InlineScript를 기본값인 false로 설정하면 별도의 요청을 통해 프록시 스크립트를 가져옵니다. 이 옵션은 여러 웹 페이지에서 같은 서비스를 참조하고 브라우저 캐싱을 사용하는 경우 유용합니다.

InlineScript를 true로 설정하면 프록시 클래스 스크립트가 페이지에 인라인 스크립트 블록으로 포함됩니다. 이렇게 하면 네트워크 요청 수가 감소하여 성능이 향상됩니다. 특히 페이지에 많은 서비스 참조가 있고 다른 페이지에서 동일한 서비스를 참조하지 않는 경우에는 더욱 효과적입니다. InlineScript를 true로 설정하면 상대 경로를 사용해야 합니다. 경로가 도메인 상대 경로이면 동일한 웹 응용 프로그램을 참조해야 합니다.

다음 예제에서는 사용자 입력을 표시하고 현재 서버 시간을 반환하는 스크립트에서 호출한 간단한 웹 서비스를 보여 줍니다. 다음 예제에서는 클라이언트 스크립트를 통해 서비스를 호출하는 페이지를 보여 줍니다.

<%@ Page Language="VB" %>

<!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;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.  
            function EchoUserInput()
            {
                var echoElem = document.getElementById("EnteredValue");
                Samples.AspNet.SimpleWebService.EchoInput(echoElem.value,
                    SucceededCallback);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function SucceededCallback(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" >
         <asp:ScriptManager  ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="SimpleWebService_VB.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Simple Web Service</h2>
                    <p>Calling a simple service that echoes the user's input and 
                        returns the current server time.</p>
                    <input id="EnteredValue" type="text" />
                    <input id="EchoButton" type="button" 
                        value="Echo" onclick="EchoUserInput()" />
            </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;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.  
            function EchoUserInput()
            {
                var echoElem = document.getElementById("EnteredValue");
                Samples.AspNet.SimpleWebService.EchoInput(echoElem.value,
                    SucceededCallback);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function SucceededCallback(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" >
         <asp:ScriptManager  ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="SimpleWebService.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Simple Web Service</h2>
                    <p>Calling a simple service that echoes the user's input and 
                        returns the current server time.</p>
                    <input id="EnteredValue" type="text" />
                    <input id="EchoButton" type="button" 
                        value="Echo" onclick="EchoUserInput()" />
            </div>
        </form>

        <hr/>

        <div>
            <span id="Results"></span>
        </div>   

    </body>

</html>

다음 예제에서는 클라이언트 스크립트를 통해 호출된 서비스를 보여 줍니다.

<%@ WebService Language="VB" Class="Samples.AspNet.SimpleWebService" %>

Imports System.Web
Imports System.Web.Services
Imports System.Xml
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

Namespace Samples.AspNet

    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <ScriptService()> _
    Public Class SimpleWebService
    Inherits System.Web.Services.WebService

    <WebMethod()>  _
    Public Function EchoInput(ByVal input As String) As String 
        Dim inputString As String = Server.HtmlEncode(input)
        If Not String.IsNullOrEmpty(inputString) Then
                Return String.Format("You entered {0}. The " + _
                "current time is {1}.", inputString, DateTime.Now)
        Else
            Return "The input string was null or empty."
        End If

    End Function 'EchoInput
End Class 'SimpleWebService 

End Namespace
<%@ WebService Language="C#" Class="Samples.AspNet.SimpleWebService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Samples.AspNet
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class SimpleWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string EchoInput(String input)
        {
            string inputString = Server.HtmlEncode(input);
            if (!String.IsNullOrEmpty(inputString))
            {
                return String.Format("You entered {0}. The "
                  + "current time is {1}.", inputString, DateTime.Now);
            }
            else
            {
                return "The input string was null or empty.";
            }
        }

    }

}

ASP.NET 웹 페이지에서 정적 메서드 호출

정적 페이지 메서드를 ASP.NET 페이지에 추가하여 웹 메서드로 한정할 수 있습니다. 그런 다음 별도의 .asmx 파일을 만들지 않고 이러한 메서드를 웹 서비스의 일부인 것처럼 해당 페이지의 스크립트에서 호출할 수 있습니다. 페이지에 웹 메서드를 만들려면 System.Web.Services 네임스페이스를 가져오고 WebMethodAttribute 특성을 노출하려는 각 정적 메서드에 추가합니다. 페이지 메서드는 페이지 메서드 호출을 수행하는 페이지에 정의해야 합니다.

웹 메서드로 정적 페이지 메서드를 호출하려면 ScriptManager 컨트롤의 EnablePageMethods 특성을 true로 설정해야 합니다.

다음 예제에서는 클라이언트 스크립트에서 정적 페이지 메서드를 호출하여 세션 상태 값을 작성하고 읽는 방법을 보여 줍니다. 다음 예제에서는 페이지 메서드를 보여 줍니다.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Services" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<script >

    <WebMethod()> _
    Public Shared Function GetSessionValue(ByVal key As String) As String
        ' Get session state value.
        Return CStr(HttpContext.Current.Session(key))

    End Function 'GetSessionValue


    <WebMethod()> _
    Public Shared Function SetSessionValue(ByVal key As String, _
    ByVal value As String) As String
        ' Set session state value.
        HttpContext.Current.Session(key) = value
        Return CStr(HttpContext.Current.Session(key))

    End Function 'SetSessionValue

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" >

    <title>Using Page Methods with Session State</title>
    <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }
            .text { font: 8pt Trebuchet MS }
    </style>
</head>

<body>

    <h2>Using Page Methods with Session State</h2>

    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1" 
             EnablePageMethods="true">
            <Scripts>
                <asp:ScriptReference Path="PageMethod.js"/>
            </Scripts>
        </asp:ScriptManager>
    </form>

     <center>
         <table>
            <tr align="left">
                <td>Write current date and time in session state:</td>
                <td>
                    <input type="button" 
                        onclick="SetSessionValue('SessionValue', Date())" 
                        value="Write" />
                </td>
            </tr>
            <tr align="left">
                <td>Read current date and time from session state:</td>
                <td>         
                    <input type="button" 
                        onclick="GetSessionValue('SessionValue')" 
                        value="Read" />
                </td>
            </tr>
        </table>           
    </center>

    <hr/>

    <span style="background-color:Aqua" id="ResultId"></span>

</body>

</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<script >

    [WebMethod]
    // Get session state value.
    public static string GetSessionValue(string key)
    {
        return (string)HttpContext.Current.Session[key];
    }

    [WebMethod]
    // Set session state value.
    public static string SetSessionValue(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
        return (string)HttpContext.Current.Session[key];
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" >

    <title>Using Page Methods with Session State</title>
    <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }
            .text { font: 8pt Trebuchet MS }
    </style>
</head>

<body>

    <h2>Using Page Methods with Session State</h2>

    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1" 
             EnablePageMethods="true">
            <Scripts>
                <asp:ScriptReference Path="PageMethod.js"/>
            </Scripts>
        </asp:ScriptManager>
    </form>

     <center>
         <table>
            <tr align="left">
                <td>Write current date and time in session state:</td>
                <td>
                    <input type="button" 
                        onclick="SetSessionValue('SessionValue', Date())" 
                        value="Write" />
                </td>
            </tr>
            <tr align="left">
                <td>Read current date and time from session state:</td>
                <td>         
                    <input type="button" 
                        onclick="GetSessionValue('SessionValue')" 
                        value="Read" />
                </td>
            </tr>
        </table>           
    </center>

    <hr/>

    <span style="background-color:Aqua" id="ResultId"></span>

</body>

</html>

다음 예제에서는 페이지 메서드를 호출하는 데 사용되는 스크립트를 보여 줍니다.

// PageMethods.js

var displayElement;

// Initializes global variables and session state.
function pageLoad()
{
    displayElement = $get("ResultId");
    PageMethods.SetSessionValue("SessionValue", Date(), 
        OnSucceeded, OnFailed);
}

// Gets the session state value.
function GetSessionValue(key) 
{
    PageMethods.GetSessionValue(key, 
        OnSucceeded, OnFailed);
}

//Sets the session state value.
function SetSessionValue(key, value) 
{
    PageMethods.SetSessionValue(key, value, 
        OnSucceeded, OnFailed);
}

// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "GetSessionValue")
    {
        displayElement.innerHTML = "Current session state value: " + 
            result;
    }
}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if(error !== null) 
    {
        displayElement.innerHTML = "An error occurred: " + 
            error.get_message();
    }
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

세션 상태에 대한 자세한 내용은 ASP.NET 세션 상태 개요를 참조하십시오.

참고 항목

작업

웹 서비스에서 UpdatePanel 컨트롤 사용

개념

ASP.NET AJAX의 웹 서비스 사용

ASP.NET AJAX의 웹 서비스 사용

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

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

ASP.NET AJAX에서 폼 인증 사용

ASP.NET AJAX에서 프로필 정보 사용