Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

customizing cshtml for each customer

I’m using .Net Framework 4.8.
I need an option in my web app to be able to override default views (just cshtml files) for each customer we have. For example consider that I have a view in folder views/account/Login.cshtml. I want to load a customized version if exists from /Views/Overrides/[MyCustomerName]/Account/Login.cshtml. How can I achieve that?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If each of your customer is having a separate instance installed (If I understand correctly! Basically I recommend to handle these things in CI/CD pipelines.) ,you can do this: First create and derive a class from 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; }
        }

    }

Then in startup.cs add these lines to replace the razor engine:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading