Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MVC controller name from controller's class

Tags:

c#

asp.net-mvc

Is there an efficient way to get the control name "HelloWorld" when all I know is the class HelloWorldController?

Maybe something like:

var str = HelloWorldController.NetExtensionMethodWhichRetursActionName(); // str = "HelloWorld" Edit: can't exist as (currently) extension method only exist for instances

or

var str = NetUtilClass.MethodWhichRetursActionNameFromControllerclass(typeof(HelloWorldController)); // str = "HelloWorld"

or something else...

I know I could write something like:

string GetName<T>() where T : Controller { var s = typeof(T).Name; return s.Delete(s.Length - "Controller".Length; }

but I guess this functionality is already available in the framework.

like image 703
Serge Intern Avatar asked Oct 17 '25 00:10

Serge Intern


1 Answers

DefaultHttpControllerSelector has a protected method to get the controller's name base on the default <controller name>Controllerclass naming convention.

Going as far as inheriting DefaultHttpControllerSelector in a utility class could do the trick. I don't need this anymore so I'm leaving the implementation to your imagination.

like image 91
Serge Intern Avatar answered Oct 19 '25 12:10

Serge Intern