あなたに追加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)
});
}