views:

163

answers:

2

I need to create a RESTful webservice in C#. This is what I have right now:

namespace WebService
{
   [ServiceContract]
   public interface IService
   {
     [OperationContract(Name="Add")]
     [WebGet(UriTemplate = "/")]
      int Add();  
   }

   public class Service:IService
   {
        public int Add()
        {
            // do some calculations and return result
            return res; 
        }
   }
}

Now, my question is How do i host this service at a location say (http://localhost/TestService) and how can i test the service in console application client?

A: 

See this answer here to get you started.

All you have to do is run this as a console app having the console run this code in Main method/

RestExample exampleService = new RestExample();

host = new ServiceHost(exampleService);

host.Open();

Be sure to throw in a

Console.WriteLine("Press any key to exit . . . .");

Console.ReadKey(true);

host.Close();

This way your service stays open until you are done.

Keep in mind you don't have to start it up as a rest service to test the implementation of the interface. In the RestExample, you can write unit test against that class to make sure each method performs as designed. Starting it as a console is an option, but to me is more integration testing rather than unit testing.

David Basarab
A: 

To host the service, WebServiceHost would be a better option. Check out this article http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webservicehost.aspx on its usage.

To test the service in a console application, you can use the HTTPWebRequest/HttpWebResponse classes to make the requests/decipher response. Check out this for the usage http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

For simple requests you could also use fiddler (in the prototyping phase of your project perhaps)

Prashanth