asp.net-mvc 在asp.net mvc中映射物理文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2834938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map the physical file path in asp.net mvc
提问by Phaedrus
I am trying to read an XSLT file from disk in my ASP.Net MVC controller. What I am doing is the following:
我正在尝试从我的 ASP.Net MVC 控制器中的磁盘读取 XSLT 文件。我正在做的是以下内容:
string filepath = HttpContext.Request.PhysicalApplicationPath;
filepath += "/Content/Xsl/pubmed.xslt";
string xsl = System.IO.File.ReadAllText(filepath);
However, half way down this thread on forums.asp.netthere is the following quote
但是,在forums.asp.net上此线程的一半有以下引用
HttpContext.Current is evil and if you use it anywhere in your mvc app you are doing something wrong because you do not need it.
HttpContext.Current 是邪恶的,如果您在 mvc 应用程序的任何地方使用它,您就做错了,因为您不需要它。
Whilst I am not using Current
, I am wondering what is the best way to determine the absolute physical path of a file in MVC? For some reason (I don't know why!) HttpContext
doesn't feel right for me.
虽然我没有使用Current
,但我想知道在 MVC 中确定文件绝对物理路径的最佳方法是什么?出于某种原因(我不知道为什么!)HttpContext
不适合我。
Is there a better (or recommended/best practice) way of reading files from disk in ASP.Net MVC?
在 ASP.Net MVC 中是否有更好(或推荐/最佳实践)从磁盘读取文件的方法?
回答by Craig Stuntz
string filePath = Server.MapPath(Url.Content("~/Content/Xsl/"));
I disagree with the idea that HttpContext.Current
is "evil." It's not the hammer for every problem, but it is certainly better than, e.g., Session for stuff that it can do OK.
我不同意HttpContext.Current
“邪恶”的想法。它不是解决所有问题的锤子,但它肯定比例如 Session 更好,因为它可以解决问题。
回答by raider33
If you're using WebApi or not specifically within a controller class, you can use the following as an alternative:
如果您正在使用 WebApi 或不是专门在控制器类中使用,则可以使用以下替代方法:
HostingEnvironment.MapPath("/Content/Xsl/pubmed.xslt")
回答by Darin Dimitrov
I would have the site root path injected into the controller constructor by the DI framework:
我将通过 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");
}
}
As far as the site root path is concerned it can be expressed with the HostingEnvironment.ApplicationPhysicalPathstatic property.
就站点根路径而言,它可以用HostingEnvironment.ApplicationPhysicalPath静态属性表示。