使用Microsoft Technologies的Web开发人员始终依赖于Server.mappath方法来解析Classic ASP和ASP.NET Web表单中的文件路径和MVC版本,最多包括5.此方法尚未包含在ASP.NET核心中,因此你使用了什么?

One of the services that's included by default when you create an ASP.NET Core application is IHostingEnvironment. The service has two properties of particular interest: ContentRootPath and WebRootPath.

ContentRootPath 解决了应用程序的基础路径。这是所在地 web.config. , project.json. , source code and other files not intended to be served to browsers. The WebRootPath property gets the physical file path to the directory that houses files intended to be browsable. By default, this is the wwwroot. 应用程序中的文件夹。

Great! So how do you access the IHostingEnvironment properties? It's easy, really. Since IHostingEnvironment is added to the application's services by the framework, you can simply inject the service into the constructor of your controller and the built-in dependency injection system will resolve it for you:

You will need to add a using directive for Microsoft.AspNetCore.Hosting to make IHostingEnvironment available to your controller class, and you will have to create a constructor for the controller.


As I mentioned, the default location of WebRootPath is the wwwroot. folder, but what if for some reason you wanted to change that? You can use the UseWebRoot extension method on the WebHostBuilder class to set your preferred location. You can do this in the Main method of the Program class: