Search code examples
c#controllerasp.net-core-webapiasp.net-core-8

How to add a Controller to a ASP.NET Core Web API


I have an ASP.NET Core 8 Web API project I am building, using .NET 8 for the first time and I can't find any info on this anywhere else. I have the standard pregenerated Program.cs file here:

using Mango.Services.CouponAPI.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(option =>
{
    option.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
ApplyMigration();

void ApplyMigration()
{
    using (var scope = app.Services.CreateScope())
    {
        var _db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        if (_db.Database.GetPendingMigrations().Count() > 0)
        {
            _db.Database.Migrate();
        }
    }
}

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
    {
        var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                (
                    DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    Random.Shared.Next(-20, 55),
                    summaries[Random.Shared.Next(summaries.Length)]
                ))
            .ToArray();
        return forecast;
    })
    .WithName("GetWeatherForecast");

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

I also have a new controller I have written that looks like this:

using System.Collections;
using Mango.Services.CouponAPI.Data;
using Mango.Services.CouponAPI.Models;
using Microsoft.AspNetCore.Mvc;

namespace Mango.Services.CouponAPI.Controller;

[Route("api/[controller]")]
[ApiController]
public class CouponAPIController : ControllerBase
{
    private readonly AppDbContext _db;

    public CouponAPIController(AppDbContext db)
    {
        _db = db;
    }

    [HttpGet]
    public object GetCoupon()
    {
        try
        {
            IEnumerable<Coupon> couponList = _db.Coupons.ToList();
            return couponList;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

When I run Swagger or Postman and try to hit this endpoint neither can find it. I deleted the WeatherForecast stuff from the Program.cs and nothing comes up in Swagger when I do so. I'm guessing it's something really simple but cant find anything in the docs or anywhere else online.


Solution

  • If you want to hit this endpoint , try to add builder.Services.AddControllers(); andapp.MapControllers();like:

    builder.Services.AddControllers();
    ...
    var app = builder.Build();
    ...
        app.MapControllers();
        
        app.Run();
    

    result:

    enter image description here