Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Building a web service that returns data

A web service lets one application offer a method to another, across a network, without either side knowing how the other is built.

The shape of the service

C#
[WebMethod]
public DataTable GetProducts(string category)
{
    using (var conn = new SqlConnection(connString))
    using (var cmd = new SqlCommand(
        "SELECT Id, Name FROM Product WHERE Category = @cat", conn))
    {
        cmd.Parameters.AddWithValue("@cat", category);
        var table = new DataTable();
        conn.Open();
        new SqlDataAdapter(cmd).Fill(table);
        return table;
    }
}

What makes it a service

  • The attribute marks the method as callable from outside.
  • The method takes simple values and returns data, so any client can use it.
  • The database work stays behind the service, hidden from the caller.
Design the contract first. Decide what the method is called and what it returns before you write the body. Other applications will depend on that shape.

Consuming it from a page is the subject of calling a web service from a page.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.