加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 来自控制器的ASP.NET MVC3 View的物理位置

发布时间:2020-12-16 10:02:01 所属栏目:asp.Net 来源:网络整理
导读:从动作中获取MVC动作所服务的View的物理位置的正确方法是什么? 我需要文件的最后修改时间来发送响应头. 解决方法 获取视图物理位置的正确方法是映射其虚拟路径.可以从BuildManagerCompiledView的ViewPath属性中检索虚拟路径(RazorView派生自该类,因此您的IV
从动作中获取MVC动作所服务的View的物理位置的正确方法是什么?

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

解决方法

获取视图物理位置的正确方法是映射其虚拟路径.可以从BuildManagerCompiledView的ViewPath属性中检索虚拟路径(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");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读