动态更改视图的路径(Change the view's path on the fly)

2019-09-29 13:57发布

我有这个类:

public abstract class MyController : Controller
{
  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      string viewPath = filterContext/*... .ViewPath*/;
      viewPath = "Some new View Path";
  }
}

我想检索和被另一个取代执行视图的路径。 我试图调试视图上的网络电话过滤器方面,但是我没能找到一个视图是即将呈现。

我怎么做?

Answer 1:

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


文章来源: Change the view's path on the fly