September 3, 2013

AddressAccessDeniedException: HTTP could not register URL http:// in Self Hosting WCF

Below Code I was using to Self Host my WCF Service.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace ConsoleApplication1
{
    [ServiceContract]
    public interface IService
    {

        [OperationContract]
        string GetData(int value);

        //written by Tanvi
        [OperationContract]
        string GetString(String theString);
    }



    public class Service : IService
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

              public string GetString(String theString)
        {
            return "Hello First WCF Service" + theString;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:81/TestService");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(Service), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);


                host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "TestService");
                // Open the ServiceHost to start listening for messages. Since
              
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }

        }
    }
}


And Got an Error "AddressAccessDeniedException: HTTP could not register URL http:// ......."
The problem was Operating System User A/c did not have enough privileges to access this address.
So When I open my Visual Studio in "Run As Administrator" Mode , Right click on visual Studio and Click on Run as Administrator, the problem was solved.