Error "Action methods on controllers annotated with ApiControllerAttribute must be attribute routed" in Web API
Hello,
I am a newbie with Web API development, and I am struggling to get a Web API that I am developing with .NET 6.0 working.
My goal is to make GetCurrentUserGroups available through the “/api/user/currentUserGroups” route but I am getting the following error message: “WebAPI.Controllers.UsersController.GetCurrentUserGroups' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed” when I try to debug the Web API locally (F5 in Visual Studio).
Here is the code:
UsersController.cs:
//[Authorize]
[Route("api")]
[ApiController]
public class UsersController : Controller
{
[HttpGet]
[Route("user/currentUserGroups")]
public async Task<JsonResult> GetCurrentUserGroups()
{
…
}
}
Program.cs:
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// 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();
app.UseAuthorization();
app.MapControllers();
app.Run();
The error occurs in the "app.MapControllers();" line.
Why do I get this error message? It is my understanding that when a Web API method is decorated with the APIController attribute, all Web API methods need a Route attribute. As you can see, my only method (GetCurrentUserGroups) has a Route attribute and that is why I don’t understand why I am getting this error.
Can you help?
Thanks,