Simplest WCF Example


You need add three projects on your solution. 2 console application, 1 class library.
1 Class library for your Service where one interface and one class will be there,
1 Console App for hosting your service,
1 Console App for consuming your service.
Reference - System.ServiceModel is needed to be added(by add reference option),
use it over using namespace option.

Now have this 3 code example over your solution.

HelloWCFClassLibrary


namespace HelloWCFClassLibrary
{
    [ServiceContract]
    public interface IHelloWCFService
    {
        [OperationContract]
        string SayHello(string msg);
    }
}




namespace HelloWCFClassLibrary
{
    public class HelloWCFService:IHelloWCFService
    {
        public string SayHello(string msg)
        {
            return string.Format("Hello" + msg);
        }
    }
}



HelloWCFServiceApplication


namespace HelloWCFServiceApplication
{
    class HelloWCFServiceHostClass
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(HelloWCFService));
            host.AddServiceEndpoint(typeof(IHelloWCFService),new BasicHttpBinding(),new Uri("http://localhost:3127/"));
            host.Open();
            Console.WriteLine("Server started");
            Console.Read();           

        }
    }
}

HelloWCFClientApp



class Program
    {
        static void Main(string[] args)
        {
            BasicHttpBinding mybinding=new BasicHttpBinding();
            EndpointAddress myaddress= new EndpointAddress("http://localhost:3127/");

            /*Below two lines is require */
            mybinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            mybinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
               
            ChannelFactory<IHelloWCFService> myChannelFactory = new ChannelFactory<IHelloWCFService>(mybinding, myaddress);
            IHelloWCFService proxy = myChannelFactory.CreateChannel();

            ((IClientChannel)proxy).Open();

            Console.WriteLine(proxy.SayHello("Pradip "));

            Console.Read();


        }
    }


That's all required to have this simplest example.

No comments:

Post a Comment