Map the physical file path in asp.net mvc
Asked Answered
R

3

41

I am trying to read an XSLT file from disk in my ASP.Net MVC controller. What I am doing is the following:

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.net there is the following quote

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.

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.

Is there a better (or recommended/best practice) way of reading files from disk in ASP.Net MVC?

Roentgen answered 14/5, 2010 at 14:34 Comment(0)
O
76
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.

Oniskey answered 14/5, 2010 at 14:40 Comment(2)
Ugh! Where is Url defined? I added System.Web.Mvc to my references (and using statements), but it is still not defined.Furnishings
It's a property of Controller msdn.microsoft.com/en-us/library/…Oniskey
B
15

If you're using WebApi or not specifically within a controller class, you can use the following as an alternative:

HostingEnvironment.MapPath("/Content/Xsl/pubmed.xslt")
Belew answered 6/5, 2015 at 0:50 Comment(0)
A
10

I would have the site root path injected into the controller constructor by the DI framework:

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.ApplicationPhysicalPath static property.

Antonia answered 15/5, 2010 at 8:13 Comment(1)
awesome idea!! People should be using more IoC in applications anyway in the .NET world...we don't use it enough.Parapodium

© 2022 - 2024 — McMap. All rights reserved.