zoukankan      html  css  js  c++  java
  • ASP.NET Core 2 学习笔记(五)静态文件

    之前的ASP.NET网站,只要把*.html*.css*.jpg*.png*.js等静态文件放在项目根目录,默认都可以直接被浏览;但ASP.NET Core 小改了浏览静态文件的方式,默认根目录不再能浏览静态文件,需要指定静态文件的目录,才可以被浏览。
    本篇将介绍ASP.NET Core浏览静态文件的方法。

    试着在项目根目录及wwwroot目录中加入静态文件,例如:

    项目根目录index.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>MyWebsite</title>
    </head>
    <body>
        项目根目录的 index.html
    </body>
    </html>

    项目根目录wwwrootindex.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>MyWebsite</title>
    </head>
    <body>
        wwwroot目录的 index.html
    </body>
    </html>
    

    然后在网址栏输入:

    • http://localhost:5000/index.html
    • http://localhost:5000/wwwroot/index.html
      会发现以上两个链接都没有办法打开index.html。

    浏览静态文件,需要Microsoft.AspNetCore.StaticFiles中间件,ASP.NET Core 2.0以上版本默认包含。

    启用静态文件

    Startup.csConfigureIApplicationBuilder使用UseStaticFiles方法注册静态文件的Middleware:

    Startup.cs

    // ...
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
    
            // ...
            
            app.Run(async context =>
            {
                await context.Response.WriteAsync("Hello World! 
    ");
            });
        }
    }
    

    UseStaticFiles默认启用静态文件的目录是wwwroot,设定完成后再次尝试开启URL:

    • http://localhost:5000/index.html
      开启的内容会是:wwwroot目录的index.html
    • http://localhost:5000/wwwroot/index.html
      依然无法显示静态文件。

    UseStaticFiles注册的顺序可以在外层一点,比较不会经过太多不必要的Middleware。如图:

    当Requset的URL文件不存在,则会转向到Run的事件(如灰色箭头)。

    变更网站目录

    默认网站目录是wwwroot,如果想要变更此目录,可以在Program.cs的WebHost Builder用UseWebRoot设置网站默认目录。
    例如:把默认网站目录wwwroot改为public,如下:

    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    
    namespace MyWebsite
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                BuildWebHost(args).Run();
            }
    
            public static IWebHost BuildWebHost(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseWebRoot("public")
                    .UseStartup<Startup>()
                    .Build();
        }
    }
    

    启用指定目录

    由于UseStaticFiles只能拿到默认文件夹底下的文件,某些情况会需要特定目录也能使用静态文件。
    例如:用npm安装的第三方库都放在项目目录底下的node_modules。

    Startup.cs

    // ...
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, @"node_modules")),
                RequestPath = new PathString("/third-party")
            });
            // ...
        }
    }
    

    以上设定就会把URL http://localhost:5000/third-party/example.js指向到项目目录 ode_modulesexample.js

    默认文件

    比较友好的用户体验会希望http://localhost:5000/可以自动指向到index.html。
    能通过UseDefaultFiles设定静态文件目录的默认文件。

    Startup.cs

    // ...
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
            // ...
        }
    }
    
    • UseDefaultFiles的职责是尝试请求默认文件。
    • UseStaticFiles 的职责是回传请求的文件。

    UseDefaultFiles必须注册在UseStaticFiles之前。
    如果先注册UseStaticFiles,当URL是/时,UseStaticFiles找不到该文件,就会直接回传找不到;所以就没有机会进到UseDefaultFiles

    自定义默认文件

    UseDefaultFiles的默认文件如下:

    • default.htm
    • default.html
    • index.htm
    • index.html

    如果默认文件的文件名不在上列清单,也可以自定义要用什么名称当作默认文件。
    通过DefaultFilesOptions设定后,传入UseDefaultFiles

    Startup.cs

    // ...
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            var defaultFilesOptions = new DefaultFilesOptions();
            defaultFilesOptions.DefaultFileNames.Add("custom.html");
            app.UseDefaultFiles(defaultFilesOptions);
            app.UseStaticFiles();
            // ...
        }
    }
    

    文件清单

    基本上为了网站安全性考量,不应该让使用者浏览服务器上面的文件清单,但如果真有需求要让使用者浏览文件清单也不是不行。

    Startup.csConfigureIApplicationBuilder使用UseFileServer方法注册文件服务器的功能:

    Startup.cs

    // ...
    public class Startup
    {
        // ...
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseFileServer(new FileServerOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, @"bin")
                ),
                RequestPath = new PathString("/StaticFiles"),
                EnableDirectoryBrowsing = true
            });
        }
    }
    

    当打开http://localhost:5000/StaticFiles时,就指向到项目目录in目录,并且可以直接浏览文件目录及文件内容,如下: 

    参考

     Working with static files in ASP.NET Core

    老司机发车啦:https://github.com/SnailDev/SnailDev.NETCore2Learning

  • 相关阅读:
    理解内存对齐
    Nodejs koa2读取服务器图片返回给前端直接展示
    nodejs koa2 设置 静态资源目录
    把 nodejs koa2 制作的后台接口 部署到 腾讯云服务器
    nodejs 更改项目端口号的 方法
    简单实现 nodejs koa2 mysql 增删改查 制作接口
    java对象的序列化以及反序列化详解
    springboot对LocalDateTime类型入参和接口返回值格式化
    js 正则exec()函数在循环中使用
    centeros 7 忘记root密码,重置
  • 原文地址:https://www.cnblogs.com/snaildev/p/9087442.html
Copyright © 2011-2022 走看看