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, eg "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 (eg 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.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.