Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Somewhere in assembly
- [assembly: AspMvcViewLocationFormat(@"~\Features\{1}\{0}.cshtml")]
- [assembly: AspMvcViewLocationFormat(@"~\Features\Shared\{0}.cshtml")]
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc(o => {
- o.Conventions.Add(new FeatureConvention());
- }).AddRazorOptions(o => {
- o.ViewLocationFormats.Clear();
- o.ViewLocationFormats.Add("/Features/{3}/{1}/{0}.cshtml");
- o.ViewLocationFormats.Add("/Features/{3}/{0}.cshtml");
- o.ViewLocationFormats.Add("/Features/Shared/{0}.cshtml");
- o.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
- });
- // ...
- }
- }
- public class FeatureViewLocationExpander : IViewLocationExpander
- {
- public void PopulateValues(ViewLocationExpanderContext context)
- {
- }
- public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
- IEnumerable<string> viewLocations)
- {
- if (context == null)
- throw new ArgumentNullException(nameof(context));
- if (viewLocations == null)
- throw new ArgumentNullException(nameof(viewLocations));
- if (context.ActionContext.ActionDescriptor is ControllerActionDescriptor descriptor
- && descriptor.Properties["feature"] is string feature) {
- foreach (var location in viewLocations) {
- yield return location.Replace("{3}", feature);
- }
- }
- }
- }
- public class FeatureConvention : IControllerModelConvention
- {
- public void Apply(ControllerModel controller)
- {
- controller.Properties.Add("feature", GetFeatureName(controller.ControllerType));
- }
- private static string GetFeatureName(TypeInfo controllerType)
- {
- var tokens = controllerType.FullName.Split('.');
- if (tokens.All(t => t != "Features")) return "";
- var featureName = tokens
- .SkipWhile(t => !t.Equals("features",
- StringComparison.OrdinalIgnoreCase))
- .Skip(1)
- .Take(1)
- .FirstOrDefault();
- return featureName;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement