Map the physical file path in asp.net mvc

前端 未结 3 1505
既然无缘
既然无缘 2021-02-02 06:57

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.PhysicalApplicat         


        
相关标签:
3条回答
  • 2021-02-02 07:03
    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.

    0 讨论(0)
  • 2021-02-02 07:04

    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.

    0 讨论(0)
  • 2021-02-02 07:21

    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")
    
    0 讨论(0)
提交回复
热议问题