Exposing WCF Services to Client Script

Windows Communication Foundation (WCF) is the Microsoft unified programming model for building service-oriented applications. It supports ASP.NET AJAX and the JavaScript Object Notation (JSON) data format. The model enables WCF services to expose functionality to Web pages that run ECMAScript (JavaScript) code and that can therefore access these services by using HTTP requests. 

If you have already created WCF services, you can add endpoints to enable script in AJAX-enabled Web pages to access those services. This topic describes how to make a WCF service available to JavaScript that runs in the browser.

The .NET Framework automatically creates JavaScript proxy classes for the WCF services at page-load time and downloads the proxy class script to the browser. These proxy classes are derived from the Sys.Net.WebServiceProxy class in the Microsoft AJAX Library. 

You can call a WCF service operation by calling the corresponding method of the JavaScript proxy class. For more information, see Calling Web Services from Client Script.

Making a WCF Service Accessible from Client Script

To make a WCF service available from client script, it must satisfy the following requirements:

  • The service must be hosted by a Web application that contains a file that has a .svc extension. This file contains an @ ServiceHost directive that points to the WCF service. The following example shows a @ ServiceHost directive.

    <%@ ServiceHost Language=C# Service="Aspnet.Samples.SimpleService" CodeBehind="~/App_Code/SimpleService.cs"%> 
    
    <%@ ServiceHost Language=VB Service="Aspnet.Samples.SimpleService" CodeBehind="~/App_Code/SimpleService.vb"%> 
    
  • You must configure the Web application to support calling Web services from script. For more information, see How to: Configure WCF Services in ASP.NET AJAX.

  • The service must be a class that implements an interface marked with ServiceContractAttribute. Individual service operations (methods) to be called from script must be qualified with the OperationContractAttribute attribute.

The following example shows a class that implements an interface that is marked with ServiceContractAttribute.

namespace Samples.Aspnet
{
    [ServiceContract(Namespace="MyServices.org")]
    public interface ISimpleService
    {
        [OperationContract]
        string HelloWorld1(string value1);
        [OperationContract]
        string HelloWorld2(DataContractType dataContractValue1);
    }

    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SimpleService : ISimpleService
    {
        public SimpleService()
        { }

        public string HelloWorld1(string value1)
        {
            return "Hello " + value1;
        }
        public string HelloWorld2(DataContractType dataContractValue1)
        {
            return "Hello " + dataContractValue1.FirstName +
                                " " + dataContractValue1.LastName;
        }
    }

    [DataContract]
    public class DataContractType
    {
        string firstName;
        string lastName;

        [DataMember]
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
        [DataMember]
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
    }
Namespace Aspnet.Samples.SimpleService

    <ServiceContract(NameSpace="MyServices.org")> _
    Public Interface ISimpleService
        <OperationContract()> _
        Function HelloWorld1(ByVal value1 As String) As String
        <OperationContract()> _
        Function HelloWorld2(ByVal dataContractValue1 _
        As DataContractType) As String
    End Interface 'ISimpleService

    <ServiceBehavior(IncludeExceptionDetailInFaults:=True), _
    AspNetCompatibilityRequirements(RequirementsMode:= _
    AspNetCompatibilityRequirementsMode.Allowed)> _
    Public Class SimpleService
        Implements ISimpleService

        Public Sub New()

        End Sub 'New

        Public Function HelloWorld1(ByVal value1 As String) As String _
        Implements ISimpleService.HelloWorld1
            Return "Hello " + value1
        End Function 'HelloWorld1

        Public Function HelloWorld2(ByVal dataContractValue1 _
        As DataContractType) As String _
        Implements ISimpleService.HelloWorld2
            Return "Hello " + dataContractValue1.FirstName + " " + _
            dataContractValue1.LastName
        End Function 'HelloWorld2
    End Class 'SimpleService

    <DataContract()> _
    Public Class DataContractType
        Private _firstName As String
        Private _lastName As String


        <DataMember()> _
        Public Property FirstName() As String
            Get
                Return _firstName
            End Get
            Set(ByVal value As String)
                _firstName = value
            End Set
        End Property

        <DataMember()> _
        Public Property LastName() As String
            Get
                Return _lastName
            End Get
            Set(ByVal value As String)
                _lastName = value
            End Set
        End Property
    End Class 'DataContractType 
End Namespace

For more information, see Creating WCF Services for ASP.NET AJAX.

Using a WCF Service from Client Script in an ASP.NET Web Page

To call a WCF service from client script in an ASP.NET Web page, you first add a ScriptManager control to the page. You then declaratively set the ServiceReference object by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the WCF service. The following example shows a service reference.

<asp:ScriptManager ID="ScriptManager1" runat="server">
  <Services>
    <asp:ServiceReference 
      Path="http://<serverhost>/SimpleService.svc"/>
  </Services>
</asp:ScriptManager>

The ServiceReference object can reference a Web service only in the same domain. The Web service path can be relative, application relative, domain relative, or absolute. For absolute paths, you must make sure that the path is in the same domain.

When a page that contains this ScriptManager control is rendered, it creates a JavaScript proxy class for the WCF service. The proxy class has functions that correspond to each service operation. The page also contains JavaScript proxy classes that correspond to server data types that are used as input parameters or return values for the Web service methods. This enables you to write client script that initializes these parameters, and to pass them to the method call.

See Also

Concepts

Using Web Services in ASP.NET AJAX

Calling Web Services from Client Script

Other Resources

Support for JSON and Other Data Transfer Formats

How to: Use Configuration to Add an ASP.NET AJAX Endpoint

Creating WCF Services for ASP.NET AJAX

How to: Create an AJAX-Enabled WCF Service and an ASP.NET Client that Accesses the Service