Skip to content

Web API Controller

Derek Peacock edited this page Dec 21, 2022 · 1 revision

Web API Controller

This is a standard way of providing online access to data on the web. This service class will have CRUD methods for:-

  1. GetAllAddresses()
  2. GetAddress(int id)
  3. PostAddress(Address address)
  4. PutAddress(int id, Address address)
  5. AddressExists(int id)

This class can be scaffolded or create from an empty API Controller. Iwas unable to get this working without removing the Async methods

namespace BlazorShoes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AddressesController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public AddressesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/Addresses
        [HttpGet]
        public List<Address> GetAddresses()
        {
            return _context.Addresses.ToList();
        }
    }
}

Registering the Controller

The Service must be registered in the program.cs class

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();

// Add Services and API Controllers

builder.Services.AddScoped<BasketService>();
builder.Services.AddScoped<AddressService>();
builder.Services.AddScoped<AddressesController>();

Clone this wiki locally