.net core 关于应用物理路径问题

1. System.IO

命名空间System.IO中存在Directory类,提供了获取应用程序运行当前目录的静态方法 System.IO.Directory.GetCurrentDirectory()=>Gets the current working directory of the application, 在.net core中此方法是执行dotnet命令所在的目录.

 class Program
    {
        static void Main(string[] args)
        {
            var directory = System.IO.Directory.GetCurrentDirectory();
            Console.WriteLine(directory);
            Console.ReadKey();
        }
    }

输出 D:\work\demo\rootpath\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2

控制台路径

2. 反射方法: 获取当前执行dll所在目录

Gets the full path or UNC location of the loaded file that contains the manifest => Assembly.GetEntryAssembly().Location

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Assembly.GetEntryAssembly().Location);
            Console.ReadKey();
        }
    }

Assembly.GetEntryAssembly().Location

3. 反射方法: 动态方式获取当前可执行类文件所在目录

    class Program
    {
        static void Main(string[] args)
        {
            dynamic type = (new Program()).GetType();
            string currentDirectory = Path.GetDirectoryName(type.Assembly.Location);
            Console.WriteLine(currentDirectory);
            Console.ReadKey();
        }
    }

动态+反射获取可执行类的路径

4. mvc/api 中获取相对路径问题

vs新建.net web application选择api后可使用注入方式引用IHostingEnvironment对象,可使用此获取路径

 public class ValuesController : ControllerBase
{
        //宿主环境
        private readonly IHostingEnvironment _hostingEnvironment;
        public ValuesController(IHostingEnvironment hostingEnvironment)
        {
            //注入宿主环境
            _hostingEnvironment = hostingEnvironment;
        }

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            //wwwroot目录路径 
            //Gets or sets the absolute path to the directory that contains the web-servable application content files
            string webRootPath = _hostingEnvironment.WebRootPath;
            //应用程序所在目录
            //Gets or sets the absolute path to the directory that contains the application content files
            string contentRootPath = _hostingEnvironment.ContentRootPath;

            return new string[] { webRootPath, contentRootPath };
      }
}

web mvc/api about rootpath

  • 注意:如果新建项目时选择的时api模式,string webRootPath = _hostingEnvironment.WebRootPath;//为null,因为默认没有wwwroot目录,且没有启用静态文件服务需要开启服务
    Startup.csConfigure中添加 app.UseStaticFiles();,并且在应用根目录中添加文件夹命名为wwwroot即可
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
       if (env.IsDevelopment())
       {
          app.UseDeveloperExceptionPage();
       }
      
       app.UseMvc();
       //开启静态文件服务  默认为wwwroot路径
       app.UseStaticFiles();
}

5. 修改mvc/api中wwwroot静态文件夹的路径

首先在wwwroot文件下放上a.txt文件内容为hello,world.
运行后访问http://localhost:58397/a.txt显示为hello,world.,说明默认静态文件起作用,如果不想在默认的应用程序下放wwwroot或者静态文件路径已经指向了固定位置,则需要使用StaticFileOptions修改默认静态文件夹的路径

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            var staticFile = new StaticFileOptions();
            staticFile.FileProvider = new PhysicalFileProvider(@"c:\data\");//指定静态文件目录
            //开启静态文件服务  默认为wwwroot路径
            app.UseStaticFiles(staticFile);
}

自定义静态文件路径

访问成功!

6. 显示静态文件路径下的所有文件

另外一个问题是,如何显示静态文件夹里的所有文件, 可以使用UseDirectoryBrowser
首先需要在ConfigureServices中注册目录浏览器,然后在Configure中使用

        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();
            }

            app.UseMvc();
            var staticFilePath = @"c:\data\";//指定静态文件目录
            var dir = new DirectoryBrowserOptions();
            dir.FileProvider = new PhysicalFileProvider(staticFilePath);
            app.UseDirectoryBrowser(dir);
            var staticFile = new StaticFileOptions();
            staticFile.FileProvider = new PhysicalFileProvider(staticFilePath);
            //开启静态文件服务  默认为wwwroot路径
            app.UseStaticFiles(staticFile);
        }

显示静态文件夹内容

浏览器默认支持浏览的格式是有限的,并且iis或其他service提供的mime也是有限的,浏览器打开不支持的文件类型的时候会报404错误,所以就需要增加配置iis的mime类型,当遇到不识别的MIME类型的时候默认为下载,或者可以在应用程序中指定部分类型为可识别类型,如.log,.conf等为文本文件格式

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc();
    var staticFilePath = @"c:\data\";//指定静态文件目录
    var dir = new DirectoryBrowserOptions();
    dir.FileProvider = new PhysicalFileProvider(staticFilePath);
    app.UseDirectoryBrowser(dir);
    var staticFile = new StaticFileOptions();
    staticFile.FileProvider = new PhysicalFileProvider(staticFilePath);
    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;

    //开启静态文件服务  默认为wwwroot路径
    app.UseStaticFiles(staticFile);
}

启用静态文件服务的简写形式

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc();
 
    app.UseFileServer(new FileServerOptions()
    {
        //此种方式貌似不支持指定mime类型,望指出如何实现
        FileProvider = new PhysicalFileProvider(@"c:\data\"),
        EnableDirectoryBrowsing = true,
    });
}

博客文章可以转载,但不可以声明为原创.
与简书 https://www.jianshu.com/nb/37455278 同步

posted @ 2019-09-01 14:41  wwmin  阅读(213)  评论(0编辑  收藏  举报