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.