自定义视图位置

using Ch05.ViewEngine.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.Extensions.DependencyInjection;

namespace Ch05.ViewEngine
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvc()
                .AddRazorOptions(options =>
                {
                    // {0} - Action Name
                    // {1} - Controller Name
                    // {2} - Area Name
                    options.ViewLocationFormats.Clear();
                    options.ViewLocationFormats.Add("/Views/{1}/{0}.cshtml");
                    options.ViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
                    options.ViewLocationFormats.Add("/Views/Shared/Layouts/{0}.cshtml");
                    options.ViewLocationFormats.Add("/Views/Shared/PartialViews/{0}.cshtml");
                    options.ViewLocationExpanders.Add(new MultiTenantViewLocationExpander());
                });

   
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
}
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Razor;

namespace Ch05.ViewEngine.Common
{
    public class MultiTenantViewLocationExpander : IViewLocationExpander
    {
        public void PopulateValues(ViewLocationExpanderContext context)
        {
            var tenant = context.ActionContext.HttpContext.Request.GetDisplayUrl();
            context.Values["tenant"] = "contoso";  //tenant;
        }

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            if (!context.Values.ContainsKey("tenant") || 
                string.IsNullOrWhiteSpace(context.Values["tenant"]))
                return viewLocations;

            var overriddenViewNames = viewLocations
                .Select(f => f.Replace("/Views/", "/Views/" + context.Values["tenant"] + "/"))
                .Concat(viewLocations)
                .ToList();
            return overriddenViewNames;
        }
    }
}
发布了496 篇原创文章 · 获赞 76 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/104774225