using System; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Dispatcher; using System.Linq; using System.Collections.Generic; public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector { private readonly HttpConfiguration _configuration; private readonly Lazy> _controllers; public NamespaceHttpControllerSelector(HttpConfiguration configuration) : base(configuration) { _configuration = configuration; _controllers = new Lazy>(InitializeControllerDictionary); } private Dictionary InitializeControllerDictionary() { var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); var assembliesResolver = _configuration.Services.GetAssembliesResolver(); var controllersResolver = _configuration.Services.GetHttpControllerTypeResolver(); var controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver); foreach (var type in controllerTypes) { var segments = type.Namespace?.Split(Type.Delimiter); var key = String.Format("{0}.{1}", segments.LastOrDefault(), type.Name.Remove(type.Name.Length - "Controller".Length)); if (!dictionary.Keys.Contains(key)) { dictionary[key] = new HttpControllerDescriptor(_configuration, type.Name, type); } } return dictionary; } public override HttpControllerDescriptor SelectController(HttpRequestMessage request) { var routeData = request.GetRouteData(); var controllerName = routeData.Values["controller"].ToString(); var namespaceName = routeData.Values["namespace"]?.ToString(); var key = String.Format("{0}.{1}", namespaceName, controllerName); if (_controllers.Value.TryGetValue(key, out var descriptor)) { return descriptor; } return null; } }