1 | using System;
|
---|
2 | using System.Collections.Concurrent;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Net.Http;
|
---|
6 | using System.Reflection;
|
---|
7 | using System.Web.Http;
|
---|
8 | using System.Web.Http.Controllers;
|
---|
9 | using System.Web.Http.Dispatcher;
|
---|
10 |
|
---|
11 | namespace HeuristicLab.Services.WebApp.Controllers {
|
---|
12 | public class WebAppHttpControllerSelector : DefaultHttpControllerSelector {
|
---|
13 | private readonly HttpConfiguration configuration;
|
---|
14 | private readonly IDictionary<string, HttpControllerDescriptor> controllers;
|
---|
15 | private readonly PluginManager pluginManager = PluginManager.Instance;
|
---|
16 |
|
---|
17 | public WebAppHttpControllerSelector(HttpConfiguration configuration)
|
---|
18 | : base(configuration) {
|
---|
19 | this.configuration = configuration;
|
---|
20 | pluginManager.Configuration = configuration;
|
---|
21 | controllers = new ConcurrentDictionary<string, HttpControllerDescriptor>();
|
---|
22 | LoadAppControllers();
|
---|
23 | }
|
---|
24 |
|
---|
25 | private void LoadAppControllers() {
|
---|
26 | var assembly = Assembly.GetExecutingAssembly();
|
---|
27 | var assemblyTypes = assembly.GetTypes();
|
---|
28 | var apiControllers = assemblyTypes.Where(c => typeof(ApiController).IsAssignableFrom(c)).ToList();
|
---|
29 | foreach (var apiController in apiControllers) {
|
---|
30 | var apiControllerName = apiController.Name.Remove(apiController.Name.Length - 10).ToLower();
|
---|
31 | controllers.Add(apiControllerName, new HttpControllerDescriptor(configuration, apiControllerName, apiController));
|
---|
32 | }
|
---|
33 | }
|
---|
34 |
|
---|
35 | public override HttpControllerDescriptor SelectController(HttpRequestMessage request) {
|
---|
36 | if (request == null) {
|
---|
37 | throw new ArgumentNullException("request");
|
---|
38 | }
|
---|
39 | var parts = request.RequestUri.AbsolutePath.Split('/');
|
---|
40 | int startIndex = parts.TakeWhile(part => part.ToLower() != "api").Count();
|
---|
41 | if (parts.Length < startIndex + 2) {
|
---|
42 | throw new ArgumentException("invalid request path");
|
---|
43 | }
|
---|
44 | string pluginName = parts[startIndex + 1].ToLower();
|
---|
45 | string controllerName = parts[startIndex + 2].ToLower();
|
---|
46 | // load controller
|
---|
47 | if (pluginName == "app") {
|
---|
48 | // from main app
|
---|
49 | HttpControllerDescriptor controller;
|
---|
50 | controllers.TryGetValue(controllerName, out controller);
|
---|
51 | return controller;
|
---|
52 | }
|
---|
53 | // from plugin
|
---|
54 | var plugin = pluginManager.GetPlugin(pluginName);
|
---|
55 | if (plugin == null) {
|
---|
56 | throw new ArgumentException(string.Format("invalid plugin '{0}'", pluginName));
|
---|
57 | }
|
---|
58 | return plugin.GetController(controllerName);
|
---|
59 | }
|
---|
60 | }
|
---|
61 | } |
---|