简体   繁体   中英

How does [controller] work in route attribute of Web API controller?

consider this code snippet:

[ApiController]
[Route("api/[controller]")]
public class HotelsController : ControllerBase
{
}

I understand that putting [controller] in the route will make the URL just api/hotels . My question is how does it do this? Does it take the whole string and cut off the part that is in the square brackets (in this case 'controller')?. Thus, I can call the class HotelsClass and put [class ] in the route and it accomplishes the same. Or, does it always have to be [controller] and it just recognizes that specific pattern?

I tried it the first way, expected it to work the same, but got an error in my application at the point where it maps the controllers, so I thought I would ask for clarity.

EDIT: I understand that the class should end in Controller and am not disputing that convention. I was just confused by the underlying mechanics of the [controller] token and how it worked, and didn't want to just blindly use something without knowing why it did what it did.

MVC and WebAPI (which is basically MVC without the V) rely on a number of conventions. One convention is that controllers ALWAYS have a name that ends with "Controller". There's no good reason to even want to break that convention, never mind to actually do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM