MSDN來自:
Controller.OnActionExecuting Method
:調用調用動作方法之前。在此階段,由於Action
尚未執行,因此不存在ActionResult
。
你最好使用OnResultExecuting
代替:
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
var viewResult = filterContext.Result as ViewResult;
if (viewResult != null)
{
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("..", "...");
viewResult.View = new RazorView(filterContext.Controller.ControllerContext, newPath, razorView.LayoutPath, razorView.RunViewStartPages, razorView.ViewStartFileExtensions);
}
base.OnResultExecuting(filterContext);
}
視圖名稱是'「指數」'或'「」'從不完整視圖路徑。我如何獲得像「〜/ Views/Controller/ViewName」這樣的字符串? – AgentFire
我相應地修改了我的答案。 – haim770
viewResult.View'屬性始終爲空,即使視圖名最初是正確的。 – AgentFire