MvcRoutePrefix.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.ApplicationModels;
  5. namespace Emby.Server.Implementations
  6. {
  7. public static class MvcRoutePrefix
  8. {
  9. public static void UseGeneralRoutePrefix(this MvcOptions opts, params string[] prefixes)
  10. {
  11. opts.Conventions.Insert(0, new RoutePrefixConvention(prefixes));
  12. }
  13. internal class RoutePrefixConvention : IApplicationModelConvention
  14. {
  15. private readonly AttributeRouteModel[] _routePrefixes;
  16. public RoutePrefixConvention(IEnumerable<string> prefixes)
  17. {
  18. _routePrefixes = prefixes.Select(p => new AttributeRouteModel(new RouteAttribute(p))).ToArray();
  19. }
  20. public void Apply(ApplicationModel application)
  21. {
  22. foreach (var controller in application.Controllers)
  23. {
  24. if (controller.Selectors == null)
  25. {
  26. continue;
  27. }
  28. var newSelectors = new List<SelectorModel>();
  29. foreach (var selector in controller.Selectors)
  30. {
  31. newSelectors.AddRange(_routePrefixes.Select(routePrefix => new SelectorModel(selector)
  32. {
  33. AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(routePrefix, selector.AttributeRouteModel)
  34. }));
  35. }
  36. controller.Selectors.Clear();
  37. newSelectors.ForEach(selector => controller.Selectors.Add(selector));
  38. }
  39. }
  40. }
  41. }
  42. }