58 lines
2.1 KiB
C#
58 lines
2.1 KiB
C#
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<Dictionary<string, HttpControllerDescriptor>> _controllers;
|
|
|
|
public NamespaceHttpControllerSelector(HttpConfiguration configuration) : base(configuration)
|
|
{
|
|
_configuration = configuration;
|
|
_controllers = new Lazy<Dictionary<string, HttpControllerDescriptor>>(InitializeControllerDictionary);
|
|
}
|
|
|
|
private Dictionary<string, HttpControllerDescriptor> InitializeControllerDictionary()
|
|
{
|
|
var dictionary = new Dictionary<string, HttpControllerDescriptor>(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;
|
|
}
|
|
}
|