Tutorial C# : Build web service from scratch in C# express

by toy

I have a very serious problem. I wanted to create a web service in C#, but my company won’t allow be to install illegal products. So, I have to install C# express edition, and one thing led to another. C# express doesn’t provide me a WebService template. Therefore, let’s roll up my sleeves and get it done.

The first thing you need to do is register the v2 .NET framework with IIS.
Run “aspnet_regiis.exe” found in “C:\WINDOWS\Microsoft.NET\Framework\v2.0.40607″

Now make a new Class Library project in C# express.
Add the System.Web.Services reference to the project

Create a new class that you want to be your web service.
Add “using System.Web.Services;” to the top of the .cs file
Make your class inherit from “System.Web.Services.WebService”
Add the [WebMethod] attribute to any methods you want to expose via the web service

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Web.Services;

namespace Examples
{
    public class MyWebService : WebService
    {
        [WebMethod]
        public string SayHello()
        {
            return "Hello World";
        }  
    }

}

Save and compile the project.

Make a new directory in c:\inetpub\wwwroot (or where ever you put you web pages). Call it “MyWebServices” or something. Create a sub-directory called “bin”.

Next add a new virtual directory to IIS that points to the “MyWebServices” directory you just made.

In the “MyWebServices” directory create a new file called “MyWebService.asmx”. Add the following line:

1
<%@ WebService Language="c#" Codebehind="MyWebService.cs" Class="Examples.MyWebService" %>

Create a “web.config” file, add the following lines:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <compilation defaultLanguage="c#" />
        <authentication mode="None" />
    </system.web>
</configuration>

Copy the .cs file, that contains the class, from the C# project to the “MyWebServices” directory

Copy the compiled DLL that C# has created into the “bin” sub-directory or “MyWebServices”

Phew, a bit of leg work but that’s the basics done.
Load your web browser and navigate to “http://localhost/MyWebServices/MyWebService.asmx“.
You should see the “SayHello” method listed. Follow the hyperlink, then click “Invoke” to test.
It should return an XML file with containing the “Hello World” message.

That’s it short and sweet.