Get the Controller Name and Method Name in ASP.NET-Core 2.2 Controller
Asked Answered
A

3

12

I know that in asp.net-core 2.2, I can get the action name as follows:

ControllerContext.ActionDescriptor.ActionName

but I am looking for a way to get the controller name of the current request/page in asp.net-core 2.2

I will appreciate any guide.

Thank you

Alaster answered 31/8, 2019 at 22:12 Comment(0)
L
20

You have access to controller name in the

ControllerContext.ActionDescriptor.ControllerName

property, given that the action descriptor is of ControllerActionDescriptor type

Reference ControllerActionDescriptor.ControllerName

Lenis answered 31/8, 2019 at 22:23 Comment(0)
G
9

I know It's late but maybe someone can benefit from it

ControllerName: ControllerContext.ActionDescriptor.ControllerName 
ActionName: ControllerContext.ActionDescriptor.ActionName
Gauntlet answered 19/4, 2020 at 16:10 Comment(0)
S
0

There are situations where your ControllerContext will be null and you end up with nothing. I recommend using reflection.

this.GetType().Name
Selfpossession answered 14/1 at 0:38 Comment(4)
this doesn't help if your contoller type name is, e.g.: ValuesController but your controller name is actually ValuesLimbic
ASP.NET MVC uses that naming convention for all controllers. Not sure what are you trying to say @Zac.Selfpossession
I'm saying that for something like Url.Action(...) where one of the parameters is a Controller name, if you pass it ValuesController like you'd get from your solution, it doesn't work, but if you pass it Values instead it does work. Your way would get ValuesController, but the accepted ControllerContext.ActionDescriptor.ControllerName gives the correct Values for that situationLimbic
Again, there are situations where your ControllerContext will be null and you end up with nothing, therefore you will pass a null value to the Url.Action()?..Using reflection you will always get the name of the controller, no matter what is the state of the context, and you can easily remove the "Controller" part safely, since, like I also mentioned this is part of a naming convention. so, steps, get the name using reflection, remove the ending "Controller" from the string..and you should be ok.Selfpossession

© 2022 - 2024 — McMap. All rights reserved.