你的位置:首页 > ASP.net教程

[ASP.net教程]mvc4根据域名切换View模板


 重写模板查找方式:

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)); }