1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Customized Message headers in WCF

Discussion in 'ASP.NET' started by MinalS, Jan 6, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    31
    Trophy Points:
    0
    There are certain requirements when user needs to request for some confidential information from the server. The information can be any login credentials or user permissions. It is not a good programming technique to expose the critical data. The information is passed is appended in the message header and is received at the server side.

    The OperationContext class is used for providing the access to the service method. The System.ServiceModel namespace contains the following class. There are several members available in the OperationContext class. We shall explore all the members in detail.

    OperationContext Constructor



    The OperationContext Constructor is used for initializing the new instance of the OperationContext class. The IContextChannel is used in the application.

    The syntax for the constructor is as shown below:

    Code:
    public OperationContext (IContextChannel channel)
    {
    }
    
    The new operation context is created using the constructor. The constructor is created within the proxy scope for applying the modifications.

    OperationContext Methods



    The following methods are present in the OperationContext.

    1) Equals ( Object ): It is used to check whether the specified object is equal to the current object. It is present in the System namespace. The syntax for the Equals method is as shown below:

    Code:
    public virtual bool Equals ( Object obj )
    
    where, obj is the current object to be compared with the current object. It returns true if the current object and the specified object are equal.

    2) GetCallbackChannel <T>: It gets the channel to the client instance calling the operation. It is present in the System.ServiceModel namespace.

    The syntax for the GetCallbackChannel is as shown below:

    Code:
    
    public T GetCallbackChannel<T> ( )
    
    
    where, T is the channel type used for calling the client back.

    3) GetType: It gets the type of the current instance. It returns the runtime type of the current instance. It is present in the System namespace. The syntax for the GetType method

    Code:
    
    public Type GetType ()
    
    
    4) GetHashCode: It is used as default hash function. It is present in the System namespace. It returns the hash code for the object. The syntax for the GetHashCode method is as shown below:

    Code:
    
    public virtual int GetHashCode()
    
    
    5) SetTransactionComplete: It is used for committing the transaction that is currently executing in the system. It is present in the System.ServiceModel namespace. The syntax for the method is as shown below:

    Code:
    
    public void SetTransactionComplete()
    
    
    6) ToString: It returns a string that is used for representing the current object. It is present in the System namespace. The syntax for the method is as shown below:

    Code:
    
    public virtual string ToString()
    
    

    OperationContext Properties



    There are several properties of the OperationContext. Every property has a specific purpose. Some of them are mentioned below:

    1) Channel: It provides user with the current channel of the OperationContext object. It is present in the System.ServiceModel namespace. The syntax for the property is as shown below:

    Code:
    
    public IContextChannel Channel { get; }
    
    
    2) Current: It gets or sets the execution context for the current thread. The System.ServiceModel namespace contains the property. The syntax for the property is as shown below:

    Code:
    
    public static OperationContext Current { get; set; }
    
    
    The System.ServiceModel.OperationContext is used for representing the messaging the execution context of the method.

    3) Extensions: It represents the collection of the extensions of the service in the message context. It is present in the System.ServiceModel namespace. The syntax is as mentioned below:

    Code:
    
    public IExtensibleCollection<OperationContext> Extensions { get; }
    
    
    It describes the collection of all extensions of the OperationContext that are used for changing the context state.

    4) HasSupportingTokens: It is used for receiving the value indicating the message has the supporting tokens. It is in the System.ServiceModel namespae. The syntax for the property is as mentioned below:

    Code:
    
    public bool HasSupportingTokens { get; }
    
    
    It returns a boolean value indicating the success and failure of the incoming message.

    5) IncomingMessageHeaders: It gets the incoming messages for the Operation Context. It is present in the System.ServiceModel. The MessageHeaders object that contains the incoming messages. The syntax for the property is as shown below:

    Code:
    
    public MessageHeaders IncomingMessageHeaders { get; }
    
    
    6) InstanceContext: It gets the InstanceContext object for the current service instance. The syntax for the property is as shown below:

    Code:
    
    public InstanceContext InstanceContext { get; }
    
    
    7) OutgoingMessageHeaders: It gets the outgoing message headers for the current OperationContext. The syntax for the property is as shown below:

    Code:
    
    public MessageHeaders OutgoingMessageHeaders { get; }
    
    

    OperationContext Events



    The OperationContext type contains the OperationCompleted event. The event is raised when the operation is completed. The syntax for the event is as shown below:

    Code:
    
    public event EventHandler OperationCompleted
    
    
    Consider an application for creating a service and a client application and demonstrate the OperationContext and MessageHeader concept in detail.

    Create a service to demonstrate the user of mathematical operations functionality. The client that consumes this service returns the result back to the calling service.

    The following steps and code to be added for creating a WCF Service is as mentioned below:

    1) Create a service interface as IService and add the appropriate attributes to it.

    Code:
    
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        int add ( int a, int b);
    
        [OperationContract]
        int mult ( int a, int b);
    
    }
    
    
    Addition and multiplication functions are added in the above code.

    2) Create a Service.cs class and implement the following code.

    Code:
    
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    
    public class Service:IService
    {
        public int add ( int a, int b)
        {
            SendResponseMessage();
            return a+b;
        }
        public int mult ( int a, int b)
        {
            SendResponseMessage();
        }
        public void SendResponseMessage ()
        {
            MessageHeader<String> mess1 = null;
            System.ServiceModel.Channels.MessageHeader header = mess1.GetUntypedHeader (“ServiceMessage”, “ns” );
            OperationContext.Current.OutgoingMessageHeaders.Add(header);
        }
    }
    
    
    3) Host the web service in the console application. The following code is added to the application.

    Code:
    
        using System;
        using System.Linq;
        using System.ServiceModel;
    
    class Program
    {
         static void Main( string[] args)
        {
            ServiceHost hs = new ServiceHost ( GetType ( MyService.Service) )
            host.Open();
            Console.WriteLine( “Service is running…Press to exit” );
        }
    }
    
    
    4) In the Web.config file, user needs to modify the configuration settings. Add the following code to the configuration file.

    Code:
    
    <system.ServiceModel>
        <services>
            <service name =”MyService.Service” behaviorConfiguration=”MyServiceBehavior” >
            <endpoint address=”Service” binding=”basicHttpBinding” contract=”IMetaDataExchange”>
            </endpoint>
            <host>
            <baseAddresses>
                <add baseAddresses=”http:localhost:8090//MyService”/>
            </baseAddresses>
            </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
            <behaviors>
            <serviceMetadata httpGetEnabled=”true” />
            <serviceDebug includeExceptionDetailInFaults=”false”/>
            </behaviors>
            </serviceBehaviors>
        </behaviors>
    </system.ServiceModel>
    
    
    5) Create a console client application and add the message header using the Operation Contract. Add the Addition function in the code. The response message is returned to the user once the service is executed.

    The following code is added to the console application.

    Code:
    
    using System;
    using System.Text;
    using System.ServiceModel;
    
    namespace ConsoleApplication1
    {
    class Program
    {
        static void Main( string[] args )
        {
            IService proxy = null;
            proxy = ChannelFactory<IService>.CreateChannel ( new BasicHttpBinding(), new EndpointAddress ( “http://localhost:8090/MyService.Service” ) );
            OperationContextScope scope = null;
            scope = New OperationContextScope ( proxy );
            Console,WriteLine (“Sum of {3}, {4} = {7}”, 4, 7, proxy.Add( 3, 4) );
            Console.WriteLine ( “Response Message : “ + OperationContext.Current.IncomingMessageHeaders.GetHeader ( Of String ) (“ServiceMessage” , “ns” ) ;
            Console.ReadLine();
        }
    }
    
    
    [ServiceContract]
    public interface IService:IClientChannel
    {
        [OperationContract]
        int add( int a, int b);
        [OperationContract]
        int mult ( int a, int b);
    }
    }
    
    
    Next, execute the host service created by the user. The following output is generated.

    [​IMG]

    Execute the client application; perform the addition of two numbers. The output and the message generated between the client and the service is as shown below:

    [​IMG]
     
    Last edited by a moderator: Jan 21, 2017

Share This Page