当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Core 2 学习笔记(五)静态文件

ASP.NET Core 2 学习笔记(五)静态文件

2018年05月29日  | 移动技术网IT编程  | 我要评论

砺剑出题系统软件,鬼吹灯之寻龙诀西瓜影音,黄薇教你变魔术

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

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

项目根目录\

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

项目根目录\wwwroot\

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

然后在网址栏输入:

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

浏览静态文件,需要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! \r\n");
        });
    }
}

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

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

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指向到项目目录\node_modules\example.js

默认文件

比较友好的用户体验会希望http://localhost:5000/可以自动指向到。
能通过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

如果默认文件的文件名不在上列清单,也可以自定义要用什么名称当作默认文件。
通过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://www.lhsxpumps.com/_localhost:5000/StaticFiles时,就指向到项目目录\bin\目录,并且可以直接浏览文件目录及文件内容,如下: 

参考

 Working with static files in ASP.NET Core

 

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网