【问题标题】:customizing cshtml for each customer为每个客户定制 cshtml
【发布时间】:2022-11-22 03:08:03
【问题描述】:

我正在使用 .Net Framework 4.8。 我的网络应用程序中需要一个选项,以便能够为我们拥有的每个客户覆盖默认视图(仅 cshtml 文件)。例如,假设我在文件夹 views/account/Login.cshtml 中有一个视图。如果存在于 /Views/Overrides/[MyCustomerName]/Account/Login.cshtml,我想加载自定义版本。我怎样才能做到这一点?

【问题讨论】:

  • 您想要什么样的定制?如果它只是静态内容(HTML/CSS/JS)那么你不能把它存储在你的数据库中吗?

标签: c# asp.net-mvc .net-4.8


【解决方案1】:

如果您的每个客户都安装了一个单独的实例(如果我理解正确的话!基本上我建议在 CI/CD 管道中处理这些事情。),您可以这样做:首先从 RazorViewEngine 创建并派生一个类:

public class MultiImplementationRazorViewEngine : RazorViewEngine
    {

        private static string _currentImplementation = /*Link to a config file to have your */;

        public MultiImplementationRazorViewEngine()
            : this(_currentImplementation)
        {
        }

        public MultiImplementationRazorViewEngine(string impl)
        {
            SetCurrentImplementation(impl);
        }

        public void SetCurrentImplementation(string impl)
        {
            if (string.IsNullOrWhiteSpace(impl))
            {
                this.ViewLocationFormats = new string[] {
                @"~/Views/{1}/{0}.cshtml",
                @"~/Views/Shared/{0}.cshtml"};
            }
            else
            {
                _currentImplementation = impl;
                ICollection<string> arViewLocationFormats =
                     new string[] { "~/Views/Overrides/" + impl + "/{1}/{0}.cshtml" };
                ICollection<string> arBaseViewLocationFormats = new string[] {
                @"~/Views/{1}/{0}.cshtml",
                @"~/Views/Shared/{0}.cshtml"};
                this.ViewLocationFormats = arViewLocationFormats.Concat(arBaseViewLocationFormats).ToArray();
            }
        }

        public static string CurrentImplementation
        {
            get { return _currentImplementation; }
        }

    }

然后在 startup.cs 中添加这些行来替换剃须刀引擎:

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MultiImplementationRazorViewEngine());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多