C
C#14mo ago
hapless.dev

✅ controller endpoint gets 404 when hit

hi everyone, im trying to make an auth web api, i managed to create an AuthService and whatnot, and my controller has only two routes, im trying to implement the /register and swagger gets it fine, but as soon as i execute the request i get 404d, why is that? i tried curl and still, could someone give me a hand?
// Controllers/AuthAPIController.cs
using Microsoft.AspNetCore.Mvc;

using Services.AuthAPI.Models.DTO;
using Services.AuthAPI.Service.IService;

namespace Services.AuthAPI.Controllers {
[Route("api/auth")]
[ApiController]
public class AuthAPIController : ControllerBase {
private readonly IAuthService _authService;
protected ResponseDTO _res;

public AuthAPIController(IAuthService authService) {
_authService = authService;
_res = new();
}

[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegistrationRequestDTO model) {
var errorMsg = await _authService.Register(model);

if (!string.IsNullOrEmpty(errorMsg)) {
_res.IsSuccess = false;
_res.Message = errorMsg;

return BadRequest(_res);
}

return Ok(_res);
}

[HttpPost("login")]
public async Task<IActionResult> Login() {
return Ok();
}
}
}
// Controllers/AuthAPIController.cs
using Microsoft.AspNetCore.Mvc;

using Services.AuthAPI.Models.DTO;
using Services.AuthAPI.Service.IService;

namespace Services.AuthAPI.Controllers {
[Route("api/auth")]
[ApiController]
public class AuthAPIController : ControllerBase {
private readonly IAuthService _authService;
protected ResponseDTO _res;

public AuthAPIController(IAuthService authService) {
_authService = authService;
_res = new();
}

[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegistrationRequestDTO model) {
var errorMsg = await _authService.Register(model);

if (!string.IsNullOrEmpty(errorMsg)) {
_res.IsSuccess = false;
_res.Message = errorMsg;

return BadRequest(_res);
}

return Ok(_res);
}

[HttpPost("login")]
public async Task<IActionResult> Login() {
return Ok();
}
}
}
No description
10 Replies
JakenVeina
JakenVeina14mo ago
404 means the route you specified doesn't exist/isn't mapped where is AuthAPIController registered?
hapless.dev
hapless.devOP14mo ago
you mean like initialized? sorry im new to .net and c# in general, i think builder.Services.AddControllers() should parse any controller that inherits from BaseController, or am i mistaken? this is how my program.cs looks like
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

using Services.AuthAPI.Data;
using Services.AuthAPI.Models;
using Services.AuthAPI.Service;
using Services.AuthAPI.Service.IService;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<AppDbContext>(option => {
option.UseSqlServer(builder.Configuration["User:DockerConnection"]);
});

// NOTE: This now makes dependency injection possible and passes the variables
// to initialize them with its environment variables
// TODO: Apply as secret
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection("ApiSettings:JwtOptions"));

// TODO: Investigate this line in depth
// IdentityRole can vary as far as I can see?
builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();

builder.Services.AddScoped<IAuthService, AuthService>();

builder.Services.AddControllers();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
// NOTE: Auth ALWAYS must be before authorization
app.UseAuthentication();
app.UseAuthorization();

ApplyMigration();
app.Run();

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

if (_db.Database.GetPendingMigrations().Count() > 0) {
_db.Database.Migrate();
}
}
}
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

using Services.AuthAPI.Data;
using Services.AuthAPI.Models;
using Services.AuthAPI.Service;
using Services.AuthAPI.Service.IService;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<AppDbContext>(option => {
option.UseSqlServer(builder.Configuration["User:DockerConnection"]);
});

// NOTE: This now makes dependency injection possible and passes the variables
// to initialize them with its environment variables
// TODO: Apply as secret
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection("ApiSettings:JwtOptions"));

// TODO: Investigate this line in depth
// IdentityRole can vary as far as I can see?
builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();

builder.Services.AddScoped<IAuthService, AuthService>();

builder.Services.AddControllers();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
// NOTE: Auth ALWAYS must be before authorization
app.UseAuthentication();
app.UseAuthorization();

ApplyMigration();
app.Run();

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

if (_db.Database.GetPendingMigrations().Count() > 0) {
_db.Database.Migrate();
}
}
}
JakenVeina
JakenVeina14mo ago
i think builder.Services.AddControllers() should parse any controller that inherits from BaseController
it should, yes you're missing routing and endpoints
UnrealSPh
UnrealSPh14mo ago
could you provide the whole model of RegistrationRequestDTO
JakenVeina
JakenVeina14mo ago
app.UseHttpsRedirection();
app.UseRouting();
// NOTE: Auth ALWAYS must be before authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseEndpoints();

ApplyMigration();
app.Run();
app.UseHttpsRedirection();
app.UseRouting();
// NOTE: Auth ALWAYS must be before authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseEndpoints();

ApplyMigration();
app.Run();
hapless.dev
hapless.devOP14mo ago
thank you so much!!! now it worked! however, i only added
builder.Services.AddRouting();
// ...
app.UseRouting();
app.MapControllers();
builder.Services.AddRouting();
// ...
app.UseRouting();
app.MapControllers();
when i tried to use app.UseEndpoints() the lsp would complain saying There is no argument given that corresponds to the required parameter 'configure' of 'EndpointRoutingApplicationBuilderExtensions.UseEndpoints(IApplicationBuilder, Action<IEndpointRouteBuilder>) im using .net 8.0, i was curious on the message and when would i need to use it or any sort of example where id encounter that, what does that error mean and why did it work without it?
JakenVeina
JakenVeina14mo ago
.MapControllers() effectively has a call to .UseEnpoints() inside of it, then what .UseEndpoints() is supposed to be is....
.UseEndpoints(endpoints =>
{
endpoints.MapGet("something", ...);
endpoints.MapPost("something-else", ...);
});
.UseEndpoints(endpoints =>
{
endpoints.MapGet("something", ...);
endpoints.MapPost("something-else", ...);
});
something to that effect I.E. it's the method by which you register all of the endpoints you want your API to respond to .MapControllers() does that for you, but by reflecting upon all of your registered controllers
hapless.dev
hapless.devOP14mo ago
i see, so and id have to map them to the specific routes on my controller i see right? like, for a more granular control over them?
JakenVeina
JakenVeina14mo ago
yeah I.E. if you're not using controllers I'm a little rusty on the specifics
hapless.dev
hapless.devOP14mo ago
aha, i see not at all, from this point i can take a look by myself, thank you so much! i was scratching my head so much around this i really really appreciate it, thank you for your quick response, patience and guidance! have a great day mate!
Want results from more Discord servers?
Add your server