Map the physical file path in asp.net mvc

好久不见. 提交于 2019-12-02 20:02:37
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.

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")

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!