Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Services.WebApp/3.3/Controllers/WebAppControllerSelector.cs @ 12428

Last change on this file since 12428 was 12428, checked in by ascheibe, 9 years ago

#2394 added web app and status page to trunk

File size: 2.5 KB
Line 
1using System;
2using System.Collections.Concurrent;
3using System.Collections.Generic;
4using System.Linq;
5using System.Net.Http;
6using System.Reflection;
7using System.Web.Http;
8using System.Web.Http.Controllers;
9using System.Web.Http.Dispatcher;
10
11namespace 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}
Note: See TracBrowser for help on using the repository browser.