How does naming of the controller path work?

I created an Azure Web API on .net core 3.1. I started with the “weatherforecast” api demo.
It works, but I do not understand how the naming of the controller works.

When I rename the Controller to “DummyController” then “magically” the path to my api is https://…/dummy. How can this be possible? How does that work?

namespace mytestapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DummyController : ControllerBase
    {
        [HttpGet]
        public string  Get()
        {
            return "wow it's magic!";
        }
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Route Attribute is a shortcut way to define custom routes without the need to make a global configuration on your startup file.
This attribute can accept common pattern among others the controller pattern

[Route("[controller]")]

so when parsing the root to this controller, it will take the name of the controller class without the suffix Controller, for your case Dummy.

Method 2

When you add the following attribute [Route (“[controller]”)] and select any name for the controller, your link will be the same name.
For example, you can say that the link to this controller is as follows:
[Route (“TestDummy”)]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x