asp.net-mvc-3 - ASP.NET MVC3 Controller View 的物理位置

标签 asp.net-mvc-3 views filepath

从 Action 内部获取将由 MVC Action 提供的 View 的物理位置的正确方法是什么?

我需要文件的最后修改时间来发送响应头。

最佳答案

获取 View 物理位置的正确方法是映射其虚拟路径。可以从 ViewPath 检索虚拟路径。 BuildManagerCompiledView 的属性(property)( RazorView 派生自该类,因此您的 IView 实例通常具有该属性)。

这是您可以使用的扩展方法:

public static class PhysicalViewPathExtension
{
    public static string GetPhysicalViewPath(this ControllerBase controller, string viewName = null)
    {
        if (controller == null)
        {
            throw new ArgumentNullException("controller");
        }

        ControllerContext context = controller.ControllerContext;

        if (string.IsNullOrEmpty(viewName))
        {
            viewName = context.RouteData.GetRequiredString("action");
        }

        var result = ViewEngines.Engines.FindView(context, viewName, null);
        BuildManagerCompiledView compiledView = result.View as BuildManagerCompiledView;

        if (compiledView != null)
        {
            string virtualPath = compiledView.ViewPath;
            return context.HttpContext.Server.MapPath(virtualPath);
        }
        else
        {
            return null;
        }
    }
}

像这样使用它:
public ActionResult Index()
{
    string physicalPath = this.GetPhysicalViewPath();
    ViewData["PhysicalPath"] = physicalPath;
    return View();
}

或者:
public ActionResult MyAction()
{
    string physicalPath = this.GetPhysicalViewPath("MyView");
    ViewData["PhysicalPath"] = physicalPath;
    return View("MyView");
}

关于asp.net-mvc-3 - ASP.NET MVC3 Controller View 的物理位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10128684/

相关文章:

java - 指定路径时文件存在无法工作

c# - ReSharper 警告 : "Static field in generic type"

c# - 如何覆盖 ASP.NET MVC 3 默认模型绑定(bind)器以在模型创建期间解决依赖关系(使用 ninject)?

asp.net-mvc - ASP.NET MVC 3 区域 - 无法使用自定义路由找到 View

如果未定义第二个过滤器,带有 2 个上下文过滤器的 Drupal 7 View 将不起作用

django - 如何通过 django-crispy-forms 中的取消按钮重定向到 url?

c# - 从 silverlight 应用程序生成当前项目的文件名列表?

asp.net-mvc-3 - 将 Html anchor 与 MVC3 路由结合使用

Drupal 和 JCarousel View - 多行

c++ - 如何使用 QSettings 在 ini 部分写入文件路径