.Net Core 獲取應用物理路徑的常見問題

如果要得到傳統的ASP.Net應用程序中的相對路徑或虛擬路徑對應的服務器物理路徑,只需要使用使用Server.MapPath()方法來取得Asp.Net根目錄的物理路徑。

但是在Asp.Net Core中不存在Server.MapPath()方法,Controller基類也沒有Server屬性。

在Asp.Net Core中取得物理路徑:

從ASP.NET Core 2.0開始,可以通過注入 IHostingEnvironment 服務對象來取得Web根目錄和內容根目錄的物理路徑,IHostingEnvironment保留了應用程序的基本信息,如下所示

   using Microsoft.AspNetCore.Hosting;
   using Microsoft.AspNetCore.Mvc;

   namespace ConsoleApp1
    {
        public class HomeController : Controller
        {
            private readonly IHostingEnvironment _hostingEnvironment;

            public HomeController(IHostingEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;
            }

            public ActionResult Index()
            {
//Web根目錄
string webRootPath = _hostingEnvironment.WebRootPath;
          //內容根目錄
string contentRootPath = _hostingEnvironment.ContentRootPath; return Content(webRootPath + "\n" + contentRootPath); } } }

 

 

 

這裏要注意區分Web根目錄 和 內容根目錄的區別:

Web根目錄是指提供靜態內容的根目錄,即asp.net core應用程序根目錄下的wwwroot目錄

內容根目錄是指應用程序的根目錄,即asp.net core應用的應用程序根目錄

在ASP.NET Core 2.0之前 (就是ASP.NET Core 1.0),通過 IApplicationEnvironment.ApplicationBasePath 來獲取 Asp.Net Core應用程序的根目錄(物理路徑) 。但是現在3都出來了,並且之前版本不完善,很多api都沒有,也就不推薦使用了。

 

當然也有其他方式獲取路徑:

System.IO

命名空間System.IO中存在Directory類,提供了獲取應用程序運行當前目錄的靜態方法 System.IO.Directory.GetCurrentDirectory()=>Gets the current working directory of the application,
在.net core中此方法不是真正的獲取應用程序的當前方法,而是執行dotnet命令所在目錄
var path = System.IO.Directory.GetCurrentDirectory();
Console.WriteLine(path);

 

輸出 C:\Users\LIKUI\source\repos\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2

 

 

控制檯路徑

2. 反射方法: 獲取當前執行dll所在目錄

 var doPath = Assembly.GetEntryAssembly().Location;
 Console.WriteLine(doPath);

 

 

 

3. 反射方法: 動態方式獲取當前可執行類文件所在目錄

dynamic type = (new Program()).GetType();
string currentDirectory = Path.GetDirectoryName(type.Assembly.Location);

 

 

 

注意:如果新建項目時選擇的時api模式,string webRootPath = _hostingEnvironment.WebRootPath;//爲null,
因爲默認沒有wwwroot目錄,且沒有啓用靜態文件服務需要開啓服務。
Startup.csConfigure中添加app.UseStaticFiles();,並且在應用根目錄中添加文件夾命名爲wwwroot即可

 

 

啓動程序Startup類:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticFiles();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

 

 

5. 修改mvc/api中wwwroot靜態文件夾的路徑

首先在wwwroot文件下放上test.txt文件內容爲測試文件。
運行後訪問http://localhost:44395/test.txt顯示爲測試文件。

說明默認靜態文件起作用,如果不想在默認的應用程序下放wwwroot或者靜態文件路徑已經指向了固定位置,則需要使用StaticFileOptions修改默認靜態文件夾的路徑

 

 比如這裏我引用本地桌面的一個文件

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            
            //引用自定義路徑靜態文件
            var path = @"C:\Users\LIKUI\Desktop\試點項目\";
            var staticFile = new StaticFileOptions();
            staticFile.FileProvider = new PhysicalFileProvider(path);
            app.UseStaticFiles(staticFile);

            app.UseHttpsRedirection();
            app.UseMvc();
        }

 

如圖:

 

 

 

      public void ConfigureServices(IServiceCollection services)
      {
        services.AddDirectoryBrowser();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      }



     public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //引用自定義文件路徑 var path = @"C:\Users\LIKUI\Desktop\試點項目\"; var staticFile = new StaticFileOptions(); staticFile.FileProvider = new PhysicalFileProvider(path); app.UseStaticFiles(staticFile); //顯示靜態文件路徑下的所有文件 var staticBrowser = new DirectoryBrowserOptions(); staticBrowser.FileProvider = new PhysicalFileProvider(path); app.UseDirectoryBrowser(staticBrowser); app.UseHttpsRedirection(); app.UseMvc(); }

 

 如圖:

 

瀏覽器默認支持瀏覽的格式是有限的,並且iis或其他service提供的mime也是有限的,所以就需要增加配置iis的mime類型,
當遇到不識別的MIME類型的時候默認爲下載,或者可以在應用程序中指定部分類型爲可識別類型,如.log,.conf等爲文本文件格式

 

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //引用自定義文件路徑
            var path = @"C:\Users\LIKUI\Desktop\試點項目\";
            var staticFile = new StaticFileOptions();
            staticFile.FileProvider = new PhysicalFileProvider(path);
            staticFile.ServeUnknownFileTypes = true;
            staticFile.DefaultContentType = "application/x-msdownload";//設置默認MIME,此處爲下載

            var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();
            fileExtensionContentTypeProvider.Mappings.Add(".log", "text/plain");//設置特定類型的MIME
            fileExtensionContentTypeProvider.Mappings.Add(".conf", "text/plain");
            staticFile.ContentTypeProvider = fileExtensionContentTypeProvider;
            app.UseStaticFiles(staticFile);

            //顯示靜態文件路徑下的所有文件
            var staticBrowser = new DirectoryBrowserOptions();
            staticBrowser.FileProvider = new PhysicalFileProvider(path);
            app.UseDirectoryBrowser(staticBrowser);

            app.UseHttpsRedirection();
            app.UseMvc();
        }

這樣就可以打開了

 

 

 

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章