.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/apiwwwroot静态文件夹的路径

首先在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错误,所以就需要增加配置iismime类型,当遇到不识别的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,
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值