13

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

0

3 Answers 3

22

You have access to controller name in the

ControllerContext.ActionDescriptor.ControllerName

property, given that the action descriptor is of ControllerActionDescriptor type

Reference ControllerActionDescriptor.ControllerName

Sign up to request clarification or add additional context in comments.

Comments

9

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

ControllerName: ControllerContext.ActionDescriptor.ControllerName 
ActionName: ControllerContext.ActionDescriptor.ActionName

Comments

0

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

this.GetType().Name

4 Comments

this doesn't help if your contoller type name is, e.g.: ValuesController but your controller name is actually Values
ASP.NET MVC uses that naming convention for all controllers. Not sure what are you trying to say @Zac.
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 situation
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.