# ASP.NET Web API

An outline for a very simple Web API project.

We're using Visual Studio 2026.

Create a new project, and use the project template *ASP&period;NET Core Web API*

Give the project a name. I've used *MyCrm*.

![1](https://cdn.hashnode.com/uploads/covers/6ae885698831ba3a85b15a4e/bd4ff671-e8b9-43df-8481-f2ef53296817.png align="center")

- I've selected *.NET 10.0 (Long Term Support)* for the framework, even though .NET 11.0 is available. I tend to stick to the even-numbered releases (LTS) unless there's something in a newer version that I particularly need.
- Leave Authentication type as *None* for now. We can add that later.
- Check *Configure for HTTPS*
- Don't check *Enable container support*
- Check *Enable OpenAPI support*
- Check *Do not use top-level statements*. That's just a matter of personal preference for me.
- Check *Use controllers*
- Don't check *Enlist in Aspire orchestration*

The template gives you a very bare-bones implementation of a weather forecast API. We don't need that, so delete the file *WeatherForecast.cs* from the main project folder, and *WeatherForecastController.cs* from the Controllers folder.

There's an option we need to set in the project settings. Right-click on the project name in the Solution Explorer and select *Properties*. Then scroll down to the Build/Output section and under *Documentation file*, check the box marked *Generate a file containing API documentation*. Leave the *XML documentation file path* empty and it'll just use the default name and location.

![2](https://cdn.hashnode.com/uploads/covers/6ae885698831ba3a85b15a4e/9103eabc-447b-43ee-a67b-624b45dff428.png align="center")

This means Visual Studio will create a standalone XML file from the comments in your code whenever it builds your project. It also generates a warning for any public classes or methods that don't have a comment, which I find helpful. The XML can be used to create automatic API documentation using something like Scalar or Swagger.

We're going to use Entity Framework Core for the database access, so we'll do that bit first. We need to install the EF Core tools.

Go to Tools/Command Line/Terminal which will open a terminal window. Type

```powershell
dotnet tool install --global dotnet-ef
```

If you have previously installed the EF Core tools and want to make sure they are up to date, type

```powershell
dotnet tool update --global dotnet-ef
```

As of today, the latest version is 11.0.0 It's OK to use version 11.0.0 of the tools with a .NET 10 project.

Now go to Tools/NuGet Package Manager/Manage NuGet Packages for Solution

Click on *Browse*, and search for "Microsoft.EntityFrameworkCore.Design". It's currently offering me version 11.0.0 because that's the latest, but that version doesn't work with a .NET 10 project. So go to the *Version* dropdown, and select the latest 10.\*.\* version. For me that's currently 10.0.15. Check your project in the list, and click *Install*. There are a couple of dialog boxes to accept.

For this little learning project, we're going to SQLite as the database. So search for "Microsoft.EntityFrameworkCore.Sqlite", and once again, change the version from 11.0.0 to whatever the latest 10.\*.\* version is. Click *Install* and accept the dialog boxes.

If you've chosen to target the latest version of the framework then you'll have no problems with mismatched versions. If you're targeting .NET 11, then you can just accept the default 11.\*.\* version of the packages. If you're reading this twelve months from now, and you're targeting .NET 12, then it'll offer you version 12.\*.\* and you'll be fine with that. It's only if there's a later version of the framework available that you have to watch what you're doing.

If you've targeted .NET 10 like me, you'll probably notice that over on the Updates tab, it's now telling you that three installed packages have updates available. This is misleading. There *are* later versions available, but it's the 11.\*.\* versions that we can't use. You can just ignore this, but if it bothers you, you can edit the \*.csproj file to suppress it.

Right-click on your project in Solution Explorer and select *Edit Project File*. You should see something like this in the middle of the file.

```xml
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
```

We have 10.0.15 because that's currently the latest version, but you might have a later version.

Where it says Version="10.0.15", that actually means "any version 10.0.15 or higher", which is why it's trying to nudge you onto 11.0.0

You can specify an acceptable range here instead, so

- `Version="[2.0,3.0]"` means "any version from 2.0 to 3.0 inclusive", so 2.0, 2.5, or 3.0 would all be OK.
- `Version="(2.0,3.0)"` means "any version higher than 2.0 and lower than 3.0", so 2.0 or 3.0 would not be OK, but 2.1, 2.5, or 2.9 would.
- `Version="[2.0,3.0)"` mixes the two, so for this one, 2.0 would be OK, but 3.0 would not.

So for ours, if we change the Version attribute on each of those three packages to `Version="[10.0.15,11.0.0)"` then we're telling it that version 10.0.15 is fine, and anything higher than that is also fine, but 11.0.0 or higher is not.

Save that file, and NuGet will stop offering you version 11.0.0, because now it knows that's not suitable. But if there's a newer 10.\*.\* version, it'll show up on the Updates tab.

To work with Entity Framework, we need some entities. Add a new folder to your project and call it *Entities*. Add a new class to that folder and call it *Customer*.

This is a very simple class to hold details of a Customer record.

The code should look like this

```c#
namespace MyCrm.Entities
{
    public class Customer
    {
        public int Id { get; set; }
        public required string Forename { get; set; }
        public required string Surname { get; set; }
        public DateOnly? DateOfBirth { get; set; }
    }
}
```

Now we need a DbContext class. Add a class to your project called *MyCrmDbContext*

```c#
using Microsoft.EntityFrameworkCore;
using MyCrm.Entities;

namespace MyCrm
{
    public class MyCrmDbContext : DbContext
    {
        public MyCrmDbContext(DbContextOptions options) : base(options) { }
        public DbSet Customers => Set();
    }
}
```

Each one of your entity classes becomes a table in the database. That's the line "public DbSet" etc.

Now we need to register the DbContext with the DI system, so open up your *Program.cs* file and add this right before the line that says "var app = builder.Build();"

```c#
    builder.Services.AddDbContext<MyCrmDbContext>(options =>
        options.UseSqlite(builder.Configuration.GetConnectionString("Default")));
```

Finally, open up *appsettings.json* and add this line

```plaintext
"ConnectionStrings": { "Default": "Data Source=mycrm.db" },
```

Build your solution just to check everything is OK. You'll see some warnings about missing comments but we'll come back to those later.

Now go back to your terminal window, move into the project folder (MyCrm\\MyCrm) and type

```powershell
dotnet ef migrations add InitialCreate
```

If that succeeds, you'll have a new folder in your project called "Migrations".

Just as a side-note, in EF Core, a "migration" is a set of instructions to create or update your database to match your C# entity classes.

So let's do that now. In your terminal window, type

```powershell
dotnet ef database update
```

That should give you a file called *mycrm.db* in your project folder

There are lots of applications for connecting to a SQLite database. I use DB Browser for SQLite (<https://sqlitebrowser.org>).

Here's the "Customers" table that it has created for you

![3](https://cdn.hashnode.com/uploads/covers/6ae885698831ba3a85b15a4e/10ea2ba9-751c-4302-8192-94f10fcf8aa8.png align="center")

And here's the CREATE TABLE command used to create it

```sql
CREATE TABLE "Customers" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_Customers" PRIMARY KEY AUTOINCREMENT,
    "Forename" TEXT NOT NULL,
    "Surname" TEXT NOT NULL,
    "DateOfBirth" TEXT NULL
)
```

You can see that EF Core has assumed that an integer property called "Id" is an auto-incrementing integer primary key. Also, that SQLite doesn't have any native date/time datatypes so it has stored the date of birth as a TEXT column.

Now onto the actual API code. Right-click on the Controllers folder and select Add/Controller...

![4](https://cdn.hashnode.com/uploads/covers/6ae885698831ba3a85b15a4e/9affe7e5-0115-443a-be3a-4f038c456776.png align="center")

Select *API* at the left and *API Controller - Empty* in the main list. There are templates that would write some of this code for you, but I tend to end up overwriting what it's written, so an empty class is easier.

```c#
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MyCrm.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase { }
}
```

First of all, that Route attribute. The bit where it says \[controller\] takes the name of the class, removes the "Controller" bit from the end, and converts it to all lower-case, so the base route for this controller would be "api/customers". The advantage here is that if you were to change the name of the class to, say "ClientsController", the route would automatically change to "api/clients". It's completely up to you, but I'm not keen on that. I think if I'm making a huge change like that, I can find the time to change the route myself. And I think hard-coding the route makes it easier to read. So I would normally change that to

```c#
[Route("api/customers")]
```

Then we need a constructor. We'll need our DbContext to access the database. The DI system will pass it in to any constructor that asks for it, so our constructor (and the private field where we store it) look like this

```c#
public CustomersController(MyCrmDbContext context)
{
    _context = context;
}

private readonly MyCrmDbContext _context;
```

Then we add the actual controller methods. They don't have to be async, but I can't think of any reason why not.

Up until recently, the standard way of doing it in a controller-based API would look like this

```c#
[HttpGet("{id:int}")]
public async Task<ActionResult<Customer>> GetCustomer([FromRoute] int id)
{
    Customer? customer = await _context.Customers.FindAsync(id);

    if(customer is null)
    {
        return NotFound();
    }

    return Ok(customer);
}
```

The client gives us the ID of the record they want in the route (e.g. /api/customers/22) and we check the database to see if it's there. If it isn't, we return a 404 (NotFound), and if it is, we return a 200 with the customer record in the response body.

But Minimal APIs introduced a new, more strongly-typed way of doing it, and it's now available for controller-based APIs too.

```c#
[HttpGet("{id:int}")]
public async Task<Results<Ok<Customer>, NotFound>> GetCustomerAsync([FromRoute] int id)
{
    Customer? customer = await _context.Customers.FindAsync(id);

    if(customer is null)
    {
        return TypedResults.NotFound();
    }

    return TypedResults.Ok(customer);
}
```

Now we're specifying in the method signature that this method can return either an OK (200) or a Not Found (404). And if it returns an OK, there'll be a Customer in the response body. The NotFound() and Ok() methods now come from the TypedResults class. That's in a different namespace so your usings at the top of the unit should look like this now

```c#
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using MyCrm.Entities;
```

We use the Results class to bundle together all the possible return types. If there is only a single return type, we don't need Results. So if this method could not return a 404, it would just look like

```c#
public async Task<Ok> GetCustomerAsync([FromRoute] int id)
```

If you manually insert some records into your Customers table, you can run the API now and call it from Postman (or even from a browser) and retrieve a Customer record.

There's another bit we should add. The database call in this method grabs a single record from a small table, so it will come back in a fraction of a second, but if you have a long-running SQL query, and somebody at the client end gets bored of waiting and cancels the request (e.g. closes the browser), the SQL query will continue to run, even though there's no point any more.

The FindAsync() method optionally takes a CancellationToken, so that you can cancel a long-running query actually while it's in progress.

So if we alter our method to also take a CancellationToken, we can pass that down to the database call.

```c#
[HttpGet("{id:int}")]
public async Task<Results<Ok<Customer>, NotFound>> GetCustomer([FromRoute] int id, CancellationToken cancellationToken)
{
    Customer? customer = await _context.Customers.FindAsync(id, cancellationToken);

    if(customer is null)
    {
        return TypedResults.NotFound();
    }

    return TypedResults.Ok(customer);
}
```

As I said, completely pointless in this case because our actual database query is going to come back almost instantly, but it's a good habit to get into.

Now we can add a method that returns a list of all the Customers in the database. In a real API we would probably return them ten at a time (or whatever page size the client requests) but here we'll just return them all.

```c#
[HttpGet]
public async Task<Ok<IEnumerable<Customer>>> GetCustomersAsync(CancellationToken cancellationToken)
{
    IEnumerable<Customer> customers = await _context.Customers.ToListAsync(cancellationToken);

  return TypedResults.Ok(customers);
}
```

This method doesn't take any parameters except the CancellationToken.

Now we can add a method to create a new Customer record.

```c#
[HttpPost]
public async Task<CreatedAtRoute<Customer>> CreateCustomerAsync([FromBody] Customer customer, CancellationToken cancellationToken)
{
    _context.Customers.Add(customer);
    await _context.SaveChangesAsync(cancellationToken);

    return TypedResults.CreatedAtRoute(customer, nameof(GetCustomerAsync), new { id = customer.Id });
}
```

Creating a new record in a REST API is a POST. We expect the details of the new record in the request body. A method like this should return a Created (201) response. It should also return the newly-created object in the response body, and pass back a "Location" header containing the URL to retrieve that record in the future. CreatedAtRoute() does all that for you.

In order to tell it which method is used to retrieve the record, we have to give the method a "Name", so the GetCustomerAsync method needs an extra bit added to its HttpGet attribute

```c#
[HttpGet("{id:int}", Name = nameof(GetCustomerAsync))]
```

Now we need a way to update an existing record

```c#
[HttpPut("{id:int}")]
public async Task<Results<NoContent,NotFound>> UpdateCustomerAsync([FromRoute] int id, [FromBody] Customer newCustomer, CancellationToken cancellationToken)
{
    Customer? customer = await _context.Customers.FindAsync([id], cancellationToken);

    if(customer is null)
    {
        return TypedResults.NotFound();
    }

    customer.Forename = newCustomer.Forename;
    customer.Surname = newCustomer.Surname;
    customer.DateOfBirth = newCustomer.DateOfBirth;

    await _context.SaveChangesAsync(cancellationToken);

    return TypedResults.NoContent();
}
```

Updating an existing record in a REST API is a PUT. It can also be a PATCH, but we'll stick to PUT for simplicity. We pass in the ID of the record to update in the route, and the details of the updated record are in the request body.

We retrieve the existing version of the record first. If it's not found, we return a 404 and go no further.

Then we update the retrieved record using the details passed in the request body, and write it back to the database. EF Core is smart enough to realise that if all the properties are the same as they were before, the actual UPDATE is unnecessary, so it skips it.

The proper HTTP status code for a successful update is 204 (No Content).

Finally, we need a way to delete a record.

```c#
[HttpDelete("{id:int}")]
public async Task<Results<NoContent, NotFound>> DeleteCustomerAsync([FromRoute] int id, CancellationToken cancellationToken)
{
    Customer? customer = await _context.Customers.FindAsync([id], cancellationToken);

    if (customer is null)
    {
        return TypedResults.NotFound();
    }

    _context.Customers.Remove(customer);
    await _context.SaveChangesAsync(cancellationToken);

    return TypedResults.NoContent();
}
```

And we have a more or less complete working API. There's still lots to do

- We need some security
- We shouldn't be passing the plain entity objects in and out; we need some DTOs
- The method that returns all of the customer records should return paged results (e.g. records 11-20 out of 25)
