Friday, May 11, 2007

How to: Expose Web Services to Client Script in AJAX

AJAX enables you to call ASP.NET Web services by using client script. There are several steps to enable the web service exposing.

1. Qualify the Web service class with the ScriptServiceAttribute attribute:


1
2
3
4
5
6
7
8
9
[ScriptService]
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
public string PrintString(String input)
{
return input;
}
}


2. Configure the Web application to support calling Web services from script. Register the ScriptHandlerFactory HTTP handler in the Web.config file for the application:


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


Note: The handler delegates the call to the default handler for Web service calls that are not issued from AJAX script.


3. Enable the Web service to be called from script in an ASP.NET Web page:


<asp:ScriptManager runat="server" ID="scriptManager">
   <Services>
      <asp:ServiceReference path="~/BL/MyWebService.asmx" />
   </Services>
</asp:ScriptManager>


Note: The ServiceReference object can reference a Web service only in the same domain.


JavaScript proxy class for the .asmx Web Service created by the page that contains the ScriptManager control. It occures when this page is rendered. The proxy class has methods that correspond to each Web method in the MyWebService.asmx service.


The next post will be about the way to call the Web Service.


 


del.icio.us tags: , ,

No comments: