mvc4根据域名切换View模板

2018-06-22 06:01:27来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 重写模板查找方式:

public class MyRazorViewEngine : RazorViewEngine
    {
        public MyRazorViewEngine() : base()
        {

        }
        private const  string DefaultView = "~/Views/";
        private const string MoblieDomain = "m.";
        private const string WwwFolder = "~/Views/www/";
        private const string MoblieFolder = "~/Views/mobile/";

        public static string GetView(HttpRequestBase request)
        {
            if (request.Url == null) return DefaultView;
            var url = request.Url.Host;
            return url.Contains(MoblieDomain) ? MoblieFolder : WwwFolder;
        }
        string GetView(ControllerContext controllerContext)
        {
            return GetView(controllerContext.HttpContext.Request);
        }
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            var views = GetView(controllerContext);
            return base.CreatePartialView(controllerContext, partialPath.Replace(DefaultView,views));
        }
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var views = GetView(controllerContext);
            return base.CreateView(controllerContext, viewPath.Replace(DefaultView, views),
                masterPath.Replace(DefaultView, views));
        }
        protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
        {
            var views = GetView(controllerContext);
            return base.FileExists(controllerContext, virtualPath.Replace(DefaultView, views));
        }
    }

Application_Start()注册

ViewEngines.Engines.Add(new MyRazorViewEngine());

_ViewStart.cshtml

 @{ Layout = "~/Views/Shared/_Layout.cshtml".Replace("~/Views/", MyRazorViewEngine.GetView(Request)); } 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:asp.net mvc 之旅 —— 第五站 从源码中分析asp.net mvc 中的Te

下一篇:MVC5为WebAPI添加命名空间的支持