Advertisement
Guest User

Untitled

a guest
May 26th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. // Somewhere in assembly
  2. [assembly: AspMvcViewLocationFormat(@"~\Features\{1}\{0}.cshtml")]
  3. [assembly: AspMvcViewLocationFormat(@"~\Features\Shared\{0}.cshtml")]
  4.  
  5. public class Startup
  6. {
  7. public void ConfigureServices(IServiceCollection services)
  8. {
  9. services.AddMvc(o => {
  10. o.Conventions.Add(new FeatureConvention());
  11. }).AddRazorOptions(o => {
  12. o.ViewLocationFormats.Clear();
  13. o.ViewLocationFormats.Add("/Features/{3}/{1}/{0}.cshtml");
  14. o.ViewLocationFormats.Add("/Features/{3}/{0}.cshtml");
  15. o.ViewLocationFormats.Add("/Features/Shared/{0}.cshtml");
  16. o.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
  17. });
  18. // ...
  19. }
  20. }
  21.  
  22. public class FeatureViewLocationExpander : IViewLocationExpander
  23. {
  24. public void PopulateValues(ViewLocationExpanderContext context)
  25. {
  26. }
  27.  
  28. public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
  29. IEnumerable<string> viewLocations)
  30. {
  31. if (context == null)
  32. throw new ArgumentNullException(nameof(context));
  33. if (viewLocations == null)
  34. throw new ArgumentNullException(nameof(viewLocations));
  35. if (context.ActionContext.ActionDescriptor is ControllerActionDescriptor descriptor
  36. && descriptor.Properties["feature"] is string feature) {
  37. foreach (var location in viewLocations) {
  38. yield return location.Replace("{3}", feature);
  39. }
  40. }
  41. }
  42. }
  43.  
  44. public class FeatureConvention : IControllerModelConvention
  45. {
  46. public void Apply(ControllerModel controller)
  47. {
  48. controller.Properties.Add("feature", GetFeatureName(controller.ControllerType));
  49. }
  50.  
  51. private static string GetFeatureName(TypeInfo controllerType)
  52. {
  53. var tokens = controllerType.FullName.Split('.');
  54. if (tokens.All(t => t != "Features")) return "";
  55. var featureName = tokens
  56. .SkipWhile(t => !t.Equals("features",
  57. StringComparison.OrdinalIgnoreCase))
  58. .Skip(1)
  59. .Take(1)
  60. .FirstOrDefault();
  61. return featureName;
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement