在asp.net mvc中映射物理文件路径

时间:2010-05-14 14:34:42

标签: asp.net-mvc filepath server.mappath

我正在尝试从ASP.Net MVC控制器中的磁盘读取XSLT文件。我正在做的是以下内容:

string filepath = HttpContext.Request.PhysicalApplicationPath;
filepath += "/Content/Xsl/pubmed.xslt";
string xsl = System.IO.File.ReadAllText(filepath);

但是,half way down this thread on forums.asp.net有以下引用

  

HttpContext.Current是邪恶的,如果你   在你的mvc应用程序的任何地方使用它   你做错了什么事   不需要它。

虽然我没有使用Current,但我想知道在MVC中确定文件的绝对物理路径的最佳方法是什么?出于某种原因(我不知道为什么!)HttpContext对我来说不合适。

ASP.Net MVC中是否有更好的(或推荐/最佳实践)方法从磁盘读取文件?

3 个答案:

答案 0 :(得分:75)

string filePath = Server.MapPath(Url.Content("~/Content/Xsl/"));

我不同意HttpContext.Current是“邪恶”的想法。对于每个问题来说,这不是锤子,但它确实比例如Session更好,它可以做得很好。

答案 1 :(得分:11)

如果您在控制器类中特别使用WebApi,则可以使用以下代码:

HostingEnvironment.MapPath("/Content/Xsl/pubmed.xslt")

答案 2 :(得分:10)

我希望DI框架将站点根路径注入到控制器构造函数中:

public class HomeController: Controller
{
    private readonly string _siteRoot;
    public HomeController(string siteRoot)
    {
        _siteRoot = siteRoot;
    }

    public ActionResult Index()
    {
        string filePath = Path.Combine(_siteRoot, @"Content\Xsl\pubmed.xslt");
        return File(filePath, "text/xml");
    }
}

就站点根路径而言,它可以用HostingEnvironment.ApplicationPhysicalPath静态属性表示。