Wednesday, 4 January 2012

Console client for a WCF Restful service protected with BASIC authentication(windows credential)

Please refer my earlier post for REST service details, below is an sample code to pass on windows credentials while calling WCF REST service(in IIS - Anonymous access is disabled and BASIC is enabled)

static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/SimpleService");

            try
            {
                WebHttpBinding binding = new WebHttpBinding();

                binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

                WebChannelFactory cf = new WebChannelFactory(binding, baseAddress);
       
                //If Default domain is not added in IIS, provide it below - else not needed
                cf.Credentials.UserName.UserName = "user";
                cf.Credentials.UserName.Password = "password";

                SimpleInterface channel = cf.CreateChannel();
               
                Console.WriteLine("Reply Hi : {0}", channel.ReplyHi("Hello, world"));
                Console.WriteLine("Reply Hii : {0}",channel.ReplyHii("Hello, world"));
             }
            catch (CommunicationException ex)
            {
                Console.WriteLine("An exception occurred: " + ex.Message);
            }
        }

No comments: