MvcRoutePrefix.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.ApplicationModels;
  5. namespace Jellyfin.Api
  6. {
  7. /// <summary>
  8. /// Route prefixing for ASP.NET MVC.
  9. /// </summary>
  10. public static class MvcRoutePrefix
  11. {
  12. /// <summary>
  13. /// Adds route prefixes to the MVC conventions.
  14. /// </summary>
  15. /// <param name="opts">The MVC options.</param>
  16. /// <param name="prefixes">The list of prefixes.</param>
  17. public static void UseGeneralRoutePrefix(this MvcOptions opts, params string[] prefixes)
  18. {
  19. opts.Conventions.Insert(0, new RoutePrefixConvention(prefixes));
  20. }
  21. private class RoutePrefixConvention : IApplicationModelConvention
  22. {
  23. private readonly AttributeRouteModel[] _routePrefixes;
  24. public RoutePrefixConvention(IEnumerable<string> prefixes)
  25. {
  26. _routePrefixes = prefixes.Select(p => new AttributeRouteModel(new RouteAttribute(p))).ToArray();
  27. }
  28. public void Apply(ApplicationModel application)
  29. {
  30. foreach (var controller in application.Controllers)
  31. {
  32. if (controller.Selectors == null)
  33. {
  34. continue;
  35. }
  36. var newSelectors = new List<SelectorModel>();
  37. foreach (var selector in controller.Selectors)
  38. {
  39. newSelectors.AddRange(_routePrefixes.Select(routePrefix => new SelectorModel(selector)
  40. {
  41. AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(routePrefix, selector.AttributeRouteModel)
  42. }));
  43. }
  44. controller.Selectors.Clear();
  45. newSelectors.ForEach(selector => controller.Selectors.Add(selector));
  46. }
  47. }
  48. }
  49. }
  50. }