我有这个类:
public abstract class MyController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
string viewPath = filterContext/*... .ViewPath*/;
viewPath = "Some new View Path";
}
}
我想检索和被另一个取代执行视图的路径。 我试图调试视图上的网络电话过滤器方面,但是我没能找到一个视图是即将呈现。
我怎么做?
从MSDN :
Controller.OnActionExecuting Method
:调用调用操作方法之前 。 在这个阶段,没有ActionResult
存在,因为Action
还不执行。
你最好使用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);
}