Error "Action methods on controllers annotated with ApiControllerAttribute must be attribute routed" in Web API

Miguel Isidoro 21 Reputation points
2022-12-07T22:44:49.827+00:00

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,

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.