006 Adding API Controller - CarrieKroutil/Reactivities GitHub Wiki

Requirements

In order for a method to be an API controller, it needs:

  1. To be decorated with [ApiController] attribute.
  2. To be decorated with [Route("[controller]")] attribute.
    • localhost:5000/{methodname_minus_controller}
      • Part before / is established in appsettings.json or respective environment file.
  3. Inherit from ControllerBase.

BaseClass

Create a new BaseApiController.cs to inherit from BaseController and perform custom steps for app.

using Microsoft.AspNetCore.Mvc;

namespace API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class BaseApiController : ControllerBase
    {
        
    }
}

New Controller Class

The http request will be routed to the appropriate controller and any outside needs should be injected into the constructor using dependency injection setup in Program.cs.

using Persistence;

namespace API.Controllers
{
    public class ActivitiesController : BaseApiController
    {
        private readonly DataContext _context;
        public ActivitiesController(DataContext context)
        {
            _context = context;
        }
    }
}
  • If used C# Extensions and “initialize field from property” didn’t generate the above, check settings.

Also, add two http endpoints as follows for a complete class:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Domain;
using Persistence;

namespace API.Controllers
{
    public class ActivitiesController : BaseApiController
    {
        private readonly DataContext _context;
        public ActivitiesController(DataContext context)
        {
            _context = context;

        }

        [HttpGet] //api/activities
        public async Task<ActionResult<List<Activity>>> GetActivities()
        {
            return await _context.Activities.ToListAsync();
        }

        [HttpGet("{id}")] //api/activities/wpmvoseml
        public async Task<ActionResult<Activity>> GetActivity(Guid id)
        {
            return await _context.Activities.FindAsync(id);
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️