Changing the Controller Suffix to Something Else in ASP.NET MVC | ASP.NET MVC Programmer Guide

In ASP.NET MVC, the Inspection whether a given Type qualifies as a controller happens inside DefaultActionDiscoveryConventions, the default IActionDiscoveryConventionsimplementation, inside of the IsController method. So we should either implement IActionDiscoveryConventionsimplementation interface ourself, or extend the DefaultActionDiscoveryConventions, which exposes all of its methods as virtual.
In the following example we extend the base logic with our new extra suffix – “Endpoint”.
We could now change our class to
And it will work just fine – the only problem is that it will be publicly available programmerguide.net/dummyendpoint – as the logic of stripping away the Controller suffix when exposing HTTP endpoints is embedded into ControllerDescriptor and handles only Controller suffix.
We should overcome such behavior by creating a custom ControllerDescriptorFactory – a factory class responsible for taking TypeInfo (describing a controller) and producing an instance of a ControllerDescriptor out of it. The Name on the ControllerDescriptor will determine how a given endpoint is publicly visible. Unfortunately at this point ControllerDescriptor has private setters, so cannot be sublassed, and the default ControllerDescriptorFactory has no virtual members, so cannot be customized – but we can work around that with a bit of reflection.
So effectively we say, if our controller ends with “Endpoint”, we are going to strip that away.
Finally, we need to register the new services against ServiceCollection used by the IBuilder. We have to do that after registering MVC, otherwise, MVC will overwrite our registrations.
And now we can see that we don’t need the mandatory “Controller” suffix anymore.
2014-06-11_1122
Be Sociable, Share!