1

I'm starting to develop in asp.NET MVC. I have a requirement to separate a Web API from View projects, I want WebAPI controllers to have different naming conventions from View project, to easily identify what is webapi controller from what is a controller for view. In both projects, the default convention is name + 'Controller'. It would be nice if there're a way to change it in webapi, example, instead of 'WebAPiController', I want the name convention to be 'WebAPICtrl' ou 'WebAPiService'.

The question that I found it's close is: change controller name convention in ASP.NET MVC

How can I archive this requirement in Asp.net mvc 5?

Community
  • 1
  • 1
  • Are you asking [how to do this in MVC 5](http://stackoverflow.com/questions/3011482/change-controller-name-convention-in-asp-net-mvc/30577420?noredirect=1#comment49228286_30577420), or Web Api 2? – alex Jun 01 '15 at 18:51
  • What about a simple folder structure - is there something "wrong" about `/api`? Perhaps that's "better" than going through the effort of going against convention? – EdSF Jun 01 '15 at 18:55
  • There're two projects, a web api, and a mvc, both use the same conventions: name + 'Controller'. It's get messy in a long term development. – Raphael Pantaleão Jun 01 '15 at 19:00

1 Answers1

6

In your Application_Start() method inside of Global.asax, you would need to replace the ControllerBuilder.Current to a custom implementation of controller factory.

 public class MvcApplication : HttpApplication
{

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        var controllerFactory = new CustomControllerFacotry();
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }
}

You'll need to a class to inherit from DefaultControllerFactory and override the CreateController method with your custom implementation. Please look at the default implementation for further guidance on how to do this. It would look something like this.

public class CustomControllerFactory : DefaultControllerFactory
{
     public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        string controllername = requestContext.RouteData.Values["controller"].ToString();       
        Type controllerType = Type.GetType(string.Format("Namespace.{0}",controllername));
        IController controller = Activator.CreateInstance(controllerType) as IController;
        return controller;

    }
}
Prime03
  • 350
  • 2
  • 9