ASP.NET: How to Create a Web Service in C#

This post shows you How to Create a simple Web Service in C# using ASP.NET

First, You need to create a new ASP.NET project. If you don't know, you can see this post How to Create ASP.NET Web Form in Visual Studio 2019.

How to create a web service in c# visual studio 2019

This is a simple example web service that allows you to insert update delete data from SQL Server.

To start creating a web service you need to follow these steps in Visual Studio.

Right-clicking on your ASP.NET project, then select Add =>New Items... => Visual C# =>Web

how to create a web service in c#

Opening your Microsoft SQL Server Management Studio, then run the sql script below.

CREATE TABLE [dbo].[Payments](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[FullName] [nvarchar](100) NULL,
	[Amount] [decimal](18, 2) NULL,
	[Note] [nvarchar](255) NULL,
	[PaymentDate] [datetime] NULL,
 CONSTRAINT [PK_Payments] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

We wil create a payments table allows you to store payments.

Next, We will use Entity Framework to connect to sql database and perform insert, update, delete actions.

Right-clicking on your project, then select Add => New Items... =>Visual C# =>Data

ado.net entity data model

Entering your model name, then click Add button.

c# entity framework

Selecting EF Designer from database, then click Next button.

entity framework database first c#

Clicking New connection button.

visual studio sql connection

Entering your sql connection information, then click OK button.

c# entity framework

Entering your connection string name, then click Next button.

c# entity framework

Selecting table you want to play demo, then enter your model namespace => Click Finish button.

entity framework security warning

Clicking OK button to continue.

c# entity framework diagram

If you get it right, you will see the following table in the diagram.

How to create web service in asp.net using c# with example

Next, Rebuild your project, then open PaymentService class.

/// <summary>
/// Summary description for PaymentService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class PaymentService : System.Web.Services.WebService
{
    
}

Creating a GetAll method allows you to get all data from payments table.

[WebMethod]
public List<Payment> GetAll()
{
    using (AppContext db = new AppContext())
    {
        return db.Payments.ToList();
    }
}

Creating an Insert method allows you to insert data to payments table.

[WebMethod]
public bool Insert(string fullName, decimal amount, string note)
{
    using (AppContext db = new AppContext())
    {
        db.Payments.Add(new Payment() { FullName = fullName, Amount = amount, Note = note, PaymentDate = DateTime.Now });
        return db.SaveChanges() > 0;
    }
}

Creating an Update method allows you to update data from payments table.

[WebMethod]
public bool Update(int id, string fullName, decimal amount, string note)
{
    using (AppContext db = new AppContext())
    {
        var obj = db.Payments.Find(id);
        if (obj != null)
        {
            obj.FullName = fullName;
            obj.Amount = amount;
            obj.Note = note;
            obj.PaymentDate = DateTime.Now;
        }
        return db.SaveChanges() > 0;
    }
}

Creating a Delete method allows you to delete record from payments table.

[WebMethod]
public bool Delete(int id)
{
    using (AppContext db = new AppContext())
    {
        var obj = db.Payments.Find(id);
        if (obj != null)
            db.Payments.Remove(obj);
        return db.SaveChanges() > 0;
    }
}

As you can see, web service is just a class that contains methods to perform a certain task and is marked above the method with the [WebMethod] property.

Press F5 to run your project, then click Insert method.

testing web service in visual studio

You can easily test the web service methods. Through this c# example, i showed you how to create a web service in c#, as well as how to use web service in asp.net c#.

Related