I have a small .NET Core test program, running in a Debian CT on Proxmox at 192.168.1.200:5000. When I test the API with Postman, the /test
endpoint works. On the same machine as well as on other machines in the same network. But when I test /api/greet
from my controller, I get an error http 404. Any idea why?
Here the successfull /test and the unsuccessfull /api/greet:
/test 200 OK
/api/greet 404 Not Found
Program.cs
:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.MapGet("/test", () => "Test route reached");
app.Run();
Controller.cs
:
namespace HelloWorldApi.Controllers
{
[ApiController]
[Route("api")]
public class HelloWorldController : ControllerBase
{
[HttpGet("greet")]
public IActionResult GetGreeting()
{
return Ok("Hello World");
}
}
}
I tried other ports, I deleted the whole code and wrote it again, I even used code from an old project that worked. Even if I put a Console.WriteLine("test") into the Constructor of the Controller, it doesn't get printed, so somehow the Controller does not get initialized?
In Program.cs you need to call
builder.Services.AddControllers();
and then after
var app = builder.Build();
do:
app.MapControllers()
Also to ensure that endpoints to your controller works add Route attribute like this:
[ApiController]
[Route("api/[controller]/[action]")]
public class HelloWorldController : ControllerBase
{
public IActionResult GetGreeting()
{
return Ok("Hello World");
}
}