Setting an alternate controller folder location in ASP.NET MVC

后端 未结 4 1534
悲&欢浪女
悲&欢浪女 2020-12-30 07:41

We can an MVC app that uses the default folder conventions for the HTML views, but we\'d like to set up alternate \"Services\" folder with controllers used only for web serv

4条回答
  •  天涯浪人
    2020-12-30 08:10

    In Asp.Net Core: I used AreaFeature library ServiceCollectionExtensions

    First set your middleware;

        services.AddMvc(options => 
            options.EnableEndpointRouting = false).
            AddFeatureFolders().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest);
    

    In the extenssion:

    return AddFeatureFolders(services, new FeatureFolderOptions());
    

    implement as according your requirement:

     public static IMvcBuilder AddFeatureFolders(this IMvcBuilder services, FeatureFolderOptions options)
            {
                if (services == null)
                    throw new ArgumentNullException(nameof(services));
    
                if (options == null)
                    throw new ArgumentException(nameof(options));
    
                var expander = new FeatureViewLocationExpander(options);
    
                services.AddMvcOptions(o => o.Conventions.Add(new FeatureControllerModelConvention(options)))
                    .AddRazorOptions(o =>
                    {
                        o.ViewLocationFormats.Clear();
                        o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\{0}.cshtml");
                        o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\_Views\{0}.cshtml");
                        o.ViewLocationFormats.Add(options.FeatureFolderName + @"\Shared\{0}.cshtml");
                        o.ViewLocationFormats.Add(options.DefaultViewLocation);
    
                        o.ViewLocationExpanders.Add(expander);
                    });
    
                return services;
            }
    

    In my case i preferred a separated _View folder for views in the features folders like that

    ~/Features/Account/_Views/login.cshtml
    ~/Features/Account/AccountController.cs
    ~/Features/Account/AccountModel.cs
    

提交回复
热议问题