Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to get a basic WCF service working on a web hosting service

4.80/5 (5 votes)
10 Oct 2011CPOL4 min read 27.1K  
Originally, I was going to create a simple Web Service using an ASMX file, but that appears to have been removed from Visual Studio 2010 - or at least I couldn't find it easily. So, WCF it is! I love the way technology lasts, don't you? Right, so I know nothing about WCF, tutorials here I come...
(This assumes your web host does support WCF services: it probably does, but check first.)

Originally, I was going to create a simple Web Service using an ASMX file, but that appears to have been removed from Visual Studio 2010 - or at least I couldn't find it easily. So, WCF it is! I love the way technology lasts, don't you? Right, so I know nothing about WCF, tutorials here I come...

Firstly, I created a separate subdomain: Services.MyDomain.com, and set up a separate FTP login to support it. This just allows me to keep services separate from the main website and makes it easier and safer for them to co-exist. If your web host doesn't support subdomains, ask them why not - or change to a paid-for hosting plan: you get what you pay for with the free ones.

Secondly, we need to create a service, and test it locally, before going anywhere near the live webhost. This is partly so that we can use the better debugging facilities, and partly so that we can later develop the service without affecting any running users - you know it makes sense!

Thirdly, we need to deploy the service to the live web host, and do final testing before we march off into the sun using it happily ever after...

So, let's create a service:
Make sure that you are running VS as an administrator: or services won't work! To always launch Visual Studio 2010 as an administrator you can create a short cut, right click the short cut, select "Properties", select the "Compatibility" tab, and check the "Run this program as an administrator" checkbox.

In VS2010, goto the File menu, "New...Web Site". Select "Web Service", and give it an appropriate name: I used SMServices because all the live web hosted stuff starts with SM to differenciate it from local stuff (it reminds me to be extra carefull with the delete key)

In the App_Code folder, open the IService.cs file and locate the TODO comment. (You can do this by opening the Tasks Pane, and double clicking the "Add your service operations here" task).
Add the code describing your service:
C#
[OperationContract]
int Add(int a, int b);

Now open the Service.cs file (also in App_Code) and add a method to the Service class which does the actual work:
C#
public int Add(int a, int b)
   {
   return a + b;
   }


Build and run your service - you should get a rather uninspiring web page which (frankly) does nothing very useful. You need a client to access the service.

This is the point at which it gets annoying. Understandable, but annoying. Run an Administrator command prompt. The easiest way is to locate the Visual Studio Command Prompty in the Microsoft Visual Studio 2010/Visual Studio Tools folder of the Start button, and right click it. Select "Run as Administrator" and deal with the UAC box.
At the command prompt, navigate to a sensible folder: somewhere you can find again. An empty folder is a good idea.
Make sure that your service is still running, and copy the command shown on the page (it will be similar to the following)
svcutil.exe http://localhost:50731/SMServices/Service.svc?wsdl
This will create two files:
output.config
service.cs


Now, we need to create the client application. In VS, use the File menu "New...Project". Select "Windows Forms Application", and give it a sensible name. In the Solution Explorer, add a Service reference (right click on "References"). Paste the address you got from the service web page:
http://localhost:50731/SMServices/Service.svc
(remembering to remove the "svcutil.exe" and "?wsdl" parts)
Press GO, then OK.

Right click your project and add an existing item: the "Service.cs" file you created earlier.

Add two text boxes for the inputs, an Add button and a text box for the output: tbParam1, tbParam2, butAddEm and tbResult. Double click the button, and add the code:
C#
private void butAddEm_Click(object sender, EventArgs e)
    {
    ServiceClient client = new ServiceClient();
    int a = int.Parse(tbParam1.Text);
    int b = int.Parse(tbParam2.Text);
    tbResult.Text = client.Add(a, b).ToString();
    }


Open the app.config file for your project (it will have been created and updated automatically). Find the part describing your service client:
HTML
<client>
    <endpoint address="http://localhost:50731/SMServices/Service.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
        contract="ServiceReference1.IService" name="BasicHttpBinding_IService" />
</client>

Remove the "ServiceReference1." part:
HTML
<client>
    <endpoint address="http://localhost:50731/SMServices/Service.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
        contract="IService" name="BasicHttpBinding_IService" />
</client>


Build your application, and run it.
If you enter two numeric values and press the button, the service will start (there will be a short delay) and the result will be displayed. Subsquent runs should not have the delay!
If you get the right result, then your service is working and ready to move to the web host.

Final part: Publish to the web host.

This was it all fell apart. I made the mistake of following the advice I found to publish the site and then copy it to the web - this didn't work.
Eventually I found:
1) Set my webhost to default to .NET 4.0, under the control panel for the web site.
2) Copy the files directly via FTP.
My web.config ended up back to normal:
XML
<?xml version="1.0"?>
<configuration>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <customErrors mode="Off"/>
    </system.web>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
</configuration>


I could then add a Service reference to the web version, remove the localhost version, and it worked. Ah...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)