1

WebAPI has a naming convention "FooController" for controller names. This is similar to ASP.NET MVC. Our codebase uses underscores to separate words in identifier named, e.g. "Foo_Bar_Object". In order for the controller names to follow this convention, we need a way to name our controllers "Foo_Controller".

Basically, we don't want URL routes to look like "oursite.com/api/foo_/", and we don't want to have to make exceptions everywhere for the underscore (e.g. route config, names of view folders, etc). To do this in MVC, we do:

Global.asax

protected void Application_Start() {

    ...

    ControllerBuilder.Current.SetControllerFactory(new Custom_Controller_Factory());
}

Custom_Controller_Factory.cs

public class Custom_Controller_Factory : DefaultControllerFactory
{
    protected override Type GetControllerType(RequestContext request_context, string controller_name)
    {
        return base.GetControllerType(request_context, controller_name + "_");
    }
}

This seems to completely take care of the problem all in once place in MVC. Is there a way to do the same for WebAPI? I've heard rumor of a DefaultHttpControllerFactory but I can't find it anywhere.

2
  • Uh what is the point of making all of this extra work for yourselves? My_Class_Name is non standard and I think anyone will suggest that you go with MyClassName. Commented Dec 5, 2014 at 22:58
  • That's purely subjective. Also, I don't decide the naming standard that my shop uses. We have decades of codebase precedent to follow. Commented Dec 5, 2014 at 23:19

1 Answer 1

2

I think DefaultHttpControllerSelector is what you are looking for.

class CustomHttpControllerSelector : DefaultHttpControllerSelector {

   public CustomHttpControllerSelector(HttpConfiguration configuration) 
      : base(configuration) { }

   public override string GetControllerName(HttpRequestMessage request) {

      IHttpRouteData routeData = request.GetRouteData();
      string controller = (string)routeData.Values["controller"]

      return controller + "_";
}

Global.asax

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new sh_Custom_Http_Controller_Selector(GlobalConfiguration.Configuration));
Sign up to request clarification or add additional context in comments.

1 Comment

This was almost exactly what I needed. I updated the answer with a few tweaks. GetControllerName needed to be override, not virtual. And I added a line for how to register it in the Global.asax. Thanks!

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.