how to create wcf service in asp.net c#

  • Open Visual Studio and select File => New => Project => WCF Service Application.
  • Now appear IService1.cs and Service1.svc page in solution explorer.
  • You can remove the default methods and class. 
  • First of all create a class and its properties in IService1.cs page like below.
 
         [DataContract]
         public class Country
        {
                [DataMember]
                public int ID { get; set; }

                [DataMember]
                public string CountryName { get; set; }
        }

(Note : Here assign a [DataContract] attribute to class and [DataMember] attribute to properties.)

  • Now create the service methods with [OperationContract] attribute within Interface like below.

       [ServiceContract]
       public interface IService1
       {
              [OperationContract]
              List<Country> GetCountry();
       }

(Note : Here the List is a return type, Country is a class name and GetCountry is a method name.)
 
  • Now go to the Service1.svc page.
  • Keep the cursor on inherited interface IService1 then appear down arrow option and click on it.
  • Under the down arrow option, Two option appear, select "implement interface IService1" option.
  • Now all methods of IService1 interface will come in Service1 page automatically like below.

      public class Service1 : IService1
      {
               public List<Country> GetCountry()
              {
                       throw new NotImplementedException();
               }
      }

  • Now type your code into the above inherited method like below  and you can remove the 
     throw new NotImplementedException();
 
      public List<Country> GetCountry()
      {
             XElement el = XElement.Load("CountryOrState.xml");
             List<Country> Coun = new List<Country>();
             Coun = (from myRow in el.Elements()

                    select new Country()
                    {
                          CountryName = myRow.Attribute("Name").Value,
                          ID = Convert.ToInt32(myRow.Attribute("ConId").Value)
                    }).Distinct().ToList();
            return Coun;
        }
 
  • Now You can give the service reference to the application.