Tuesday, March 12, 2013

Get the binding used to call wcf service in implementation code

This is about how to find out what is the binding used to call WCF at service implementation method. These type of situation may come when you develop a WCF based application which exposes net.tcp binding to internal / intranet users and http binding to external public users. In the ideal case the service request must be processed in same way for external and internal users. But rarely there may be requirements to process it differently and in those scenarios we need to programatically determine how the service is called or which binding is used to invoke the WCF service. Below is the code to deal with the same.

string binding = OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.Scheme;


The OperationContext is an important class when you want to deal with these kind of things. Its thread static property Current gives the details about current operation.You may explore that to find more details such as security and other stuff. The whole service side can be as follows.



    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            string binding = OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.Scheme;
            return string.Format("Hello, {0}.You called me using {1} binding", name,binding);
        }
    }

No comments: