1

In ASP.NET MVC, how can we make controller classes without using "controller" suffix? I couldn't find a solution on the web. MSDN documentation says that a controller class name must ends with "controller".

Can some expert help me out?

Thank you.

Jerry

3
  • 2
    Why would you want to make a controller without the suffix? That's how the framework works. Commented Jul 11, 2012 at 14:19
  • Yes you can. But like @jesse i'm curious to know why you want do this? Commented Jul 11, 2012 at 14:20
  • While it can be done, it places more of a burden on you if you do so. Frameworks are designed to improve productivity by following a set plan. If you want to deviate from that plan significantly, there is little value in using the framework in the first place. Commented Jul 11, 2012 at 15:54

1 Answer 1

2

You have to use a custom controller factory by inheriting the DefaultControllerFactory and override the GetControllerType method.

// instantiate controllers that doesn't have "Controller" suffix.
public class CustomControllerFactory: DefaultControllerFactory
{ 
    protected override Type GetControllerType(System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        var controllersNs = "MvcApp.Controllers";
        return Type.GetType(string.Format("{0}.{1}", controllersNs, controllerName));
    }
}

And you have to register this controller factory in Global.asax.cs.

ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());

Important: The DefaultControllerFactory does more work to improve the performance by caching the types and other stuff, you have to look into the source code to get a better idea.

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

1 Comment

Thank you all for the answers. I am just curious to see how MVC worked internally. Every time I have to make sure that my controller class has "controller" suffix in it. Based on the link provided by the answer, I know how that works now.

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.