Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

ServiceContractAttribute Class

Indicates that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application.

System.Object
  System.Attribute
    System.ServiceModel.ServiceContractAttribute

Namespace:  System.ServiceModel
Assemblies:   System.ServiceModel (in System.ServiceModel.dll)
  System.ServiceModel.Primitives (in System.ServiceModel.Primitives.dll)

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Interface, Inherited = false, 
	AllowMultiple = false)]
public sealed class ServiceContractAttribute : Attribute

The ServiceContractAttribute type exposes the following members.

  NameDescription
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsServiceContractAttributeInitializes a new instance of the ServiceContractAttribute class.
Top

  NameDescription
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsCallbackContractGets or sets the type of callback contract when the contract is a duplex contract.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsConfigurationNameGets or sets the name used to locate the service in an application configuration file.
Public propertyHasProtectionLevelGets a value that indicates whether the member has a protection level assigned.
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsNameGets or sets the name for the <portType> element in Web Services Description Language (WSDL).
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsNamespaceGets or sets the namespace of the <portType> element in Web Services Description Language (WSDL).
Public propertyProtectionLevelSpecifies whether the binding for the contract must support the value of the ProtectionLevel property.
Public propertySessionModeGets or sets whether sessions are allowed, not allowed or required.
Public propertyTypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Top

  NameDescription
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public methodMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate method_Attribute.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.InvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top

Use the ServiceContractAttribute attribute on an interface (or class) to define a service contract. Then use the OperationContractAttribute attribute on one or more of the class (or interface) methods to define the contract's service operations. When the service contract is implemented and combined with a Windows Communication Foundation Bindings and an EndpointAddress object, the service contract is exposed for use by clients. For an overview of the process using simple examples, see Getting Started Tutorial. For more information about creating service contracts, see Designing and Implementing Services.

The information expressed by a ServiceContractAttribute and its interface is loosely related to the Web Services Description Language (WSDL) <portType> element. A service contract is used on the service side to specify what the service’s endpoint exposes to callers. It is also used on the client side to specify the contract of the endpoint with which the client communicates and, in the case of duplex contracts, to specify the callback contract (using the CallbackContract property) that the client must implement in order to participate in a duplex conversation.

NoteNote

An interface or class that is decorated with ServiceContractAttribute must also have at least one method marked with the OperationContractAttribute attribute to expose any functionality. See the Examples section for a code example of the simplest use of the two attributes to define and implement a service.

Use the ServiceContractAttribute properties to modify the service contract.

  • The ConfigurationName property specifies the name of the service element in the configuration file to use.

  • The Name and Namespace properties control the name and namespace of the contract in the WSDL <portType> element.

  • The SessionMode property specifies whether the contract requires a binding that supports sessions.

  • The CallbackContract property specifies the return contract in a two-way (duplex) conversation.

  • The HasProtectionLevel and ProtectionLevel properties indicate whether all messages supporting the contract have a explicit ProtectionLevel value, and if so, what that level is.

Services implement service contracts, which represent the data exchange that a service type supports. A service class can implement a service contract (by implementing an interface marked with ServiceContractAttribute that has methods marked with OperationContractAttribute) or it can be marked with the ServiceContractAttribute and apply the OperationContractAttribute attribute to its own methods. (If a class implements an interface marked with ServiceContractAttribute, it cannot be itself marked with ServiceContractAttribute.) Methods on service types that are marked with the OperationContractAttribute are treated as part of a default service contract specified by the service type itself. For details about service operations, see OperationContractAttribute.

By default, the Name and Namespace properties are the name of the contract type and http://tempuri.org, respectively, and ProtectionLevel is ProtectionLevel.None. It is recommended that service contracts explicitly set their names, namespaces, and protection levels using these properties. Doing so accomplishes two goals. First, it builds a contract that is not directly connected to the managed type information, enabling you to refactor your managed code and namespaces without breaking the contract as it is expressed in WSDL. Second, explicitly requiring a certain level of protection on the contract itself enables the runtime to validate whether the binding configuration supports that level of security, preventing poor configuration from exposing sensitive information. For more information about protection levels, see Understanding Protection Level.

To expose a service for use by client applications, create a host application to register your service endpoint with Windows Communication Foundation (WCF). You can host WCF services using Windows Activation Services (WAS), in console applications, Windows Service applications, ASP.NET applications, Windows Forms applications, or any other kind of application domain.

Hosting in the WAS is very similar to creating an ASP.NET application. For details, see How to: Host a WCF Service in IIS.

Clients either use the service contract interface (the interface marked with ServiceContractAttribute) to create a channel to the service or they use the client objects (which combine the type information of the service contract interface with the ClientBase<TChannel> class) to communicate with your service. For details on client channels to services, see the ChannelFactory<TChannel> class and WCF Client Overview.

Using a ServiceContractAttribute class or interface to inherit from another ServiceContractAttribute class or interface extends the parent contract. For example, if an IChildContract interface is marked with ServiceContractAttribute and inherited from another service contract interface, IParentContract, the IChildContract service contract contains the methods of both IParentContract and IChildContract. Extending contracts (whether on classes or interfaces) is very similar to extending managed classes and interfaces.

The most flexible approach to creating services is to define service contract interfaces first and then have your service class implement that interface. (This is also the simplest way to build your services if you must implement service contracts that have been defined by others.) Building services directly by marking a class with ServiceContractAttribute and its methods with OperationContractAttribute works when the service exposes only one contract (but that contract can be exposed by more than one endpoint).

Use the CallbackContract property to indicate another service contract that, when bound together with the original service contract, define a message exchange that can flow in two ways independently. For details, see CallbackContract.

The following code example shows how to apply the ServiceContractAttribute to an interface to define a service contract with one service method, indicated by the OperationContractAttribute. In this case, the protection level required of bindings for all messages is ProtectionLevel.EncryptAndSign.

The code example then implements that contract on the SampleService class.

using System;
using System.Collections.Generic;
using System.Net.Security;
using System.ServiceModel;
using System.Text;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Namespace="http://microsoft.wcf.documentation",
    Name="SampleService",
    ProtectionLevel=ProtectionLevel.EncryptAndSign
  )]
  public interface ISampleService{
    [OperationContract]
    string SampleMethod(string msg);
  }

  class SampleService : ISampleService
  {
  #region ISampleService Members

  public string  SampleMethod(string msg)
  {
 	  return "The service greets you: " + msg;
  }

  #endregion
  }
}

The following code example shows a simple configuration file for the preceding service that creates one endpoint.

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="mex"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mex">
          <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="mex"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mex">
          <serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

The following code example shows a simple client that invokes the preceding SampleService.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

public class Client
{
  public static void Main()
  {
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient();
    try
    {
        // Making calls.
        Console.WriteLine("Enter the greeting to send: ");
        string greeting = Console.ReadLine();
        Console.WriteLine("The service responded: " + wcfClient.SampleMethod(greeting));

        Console.WriteLine("Press ENTER to exit:");
        Console.ReadLine();

        // Done with service. 
        wcfClient.Close();
        Console.WriteLine("Done!");
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      wcfClient.Abort();
      Console.Read();
    }
    catch(CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message);
      wcfClient.Abort();
      Console.Read();
    }
  }
}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft