Search code examples
asp.net-mvcasp.net-core

can't use [Route("")] on strings while school examples show it does


So I'm working on school tasks and up until now everything worked and made sense. But right now I'm creating routes using controllers and the example code doesn't work locally. This is the code:

using Microsoft.AspNetCore.Components;

namespace HelloCoreEmpty.Controllers
{
    [Route("about")]
    public class AboutController
    {
        [Route("")]
        public string Phone()
        {
            return "Test";
        }
    }
}

The first [Route] works but the latter ones return this error:

"attribute route is not valid on this declaration type"


Solution

  • Check your using statement. You probably meant to reference Microsoft.AspNetCore.Mvc instead of Microsoft.AspNetCore.Components:

    using Microsoft.AspNetCore.Mvc;
    // NOT: using Microsoft.AspNetCore.Components;
    

    The RouteAttribute from the Mvc namespace can be used on both classes and methods, whereas the RouteAttribute from the Components namespace can be used only on classes, not methods — which would explain the compiler error you're getting when you try to apply the attribute to methods.