添加到您的Base/Controller
:
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
var viewResult = filterContext.Result as ViewResult;
if (viewResult != null)
{
string env = ... // determine your environment somehow
var razorEngine = viewResult.ViewEngineCollection.OfType<RazorViewEngine>().Single();
var viewName = !String.IsNullOrEmpty(viewResult.ViewName) ? viewResult.ViewName : filterContext.RouteData.Values["action"].ToString();
var razorView = razorEngine.FindView(filterContext.Controller.ControllerContext, viewName, viewResult.MasterName, false).View as RazorView;
var currentPath = razorView.ViewPath;
var newPath = currentPath.Replace(".cshtml", env + ".cshtml");
if (razorEngine.FileExists(filterContext.Controller.ControllerContext, newPath))
viewResult.View = new RazorView(filterContext.Controller.ControllerContext, newPath, razorView.LayoutPath, razorView.RunViewStartPages, razorView.ViewStartFileExtensions);
}
base.OnResultExecuting(filterContext);
}
此外,如果您使用的是 MVC 4(因此是WebPages
2.0),您可以使用DisplayModeProvider
它轻松实现此目的。
在你的Global.asax
:
protected void Application_Start()
{
DisplayModeProvider.Instance.Modes.Add(new DefaultDisplayMode("debug")
{
ContextCondition = (context => context.IsDebuggingEnabled)
});
DisplayModeProvider.Instance.Modes.Add(new DefaultDisplayMode("test")
{
ContextCondition = (context => context.Request.IsLocal)
});
}