ASP.NET MVC3控制器视图的物理位置 [英] ASP.NET MVC3 Physical Location of View from controller

查看:62
本文介绍了ASP.NET MVC3控制器视图的物理位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the proper way to get the physical location of the View that will be served by a MVC action from inside the action?

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

I need the last modified time of the file for sending response headers.

推荐答案

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

The proper way to the get physical location of a view is to map its virtual path. The virtual path can be retrieved from the ViewPath property of BuildManagerCompiledView (RazorView derive from that class, and your IView instances will therefore typically have that property).

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

Here is an extension method that you can use:

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 MVC3控制器视图的物理位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆