asp.net core 使用 StaticFiles 中间件 (不完整翻译)

原文地址:https://docs.asp.net/en/latest/fundamentals/static-files.html

设置静态资源根目录

Startup.cs 中的 Configure 方法中使用 StaticFiles 中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles(); // 使用默认的静态资源文件夹 /wwwroot

    // 使用指定的 /StaticFiles 文件夹
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
        RequestPath = new PathString("/StaticFiles")
    });
}

启用目录浏览功能

Startup.Configure 中添加下面的代码

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
    RequestPath = new PathString("/MyImages")
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
        RequestPath = new PathString("/MyImages")
    });

然后在 Startup.ConfigureServices 中调用 AddDirectoryBrowser 拓展方法

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}

这样,我们就可以通过 http://<app>/MyImages 来浏览 wwwroot/images 文件夹。

提供默认文档

设置一个默认的主页以便网站的访问者可以开始他们的浏览。为了能让你的网站在访客在不用提供完整页面路径的情况下能显示出默认页面,我们需要从 Startup.Configure 中调用 UseDefaultFiles 拓展方法。

public void Configure(IApplicationBuilder app)
{
    app.UseDefaultFiles();
    app.UseStaticFiles();
}

注意
UseDefaultFile 必须在 UseStaticFiles 之前调用来提供默认页面。
UseDefaultFile 只是一个 URL 重写组件,它并不会真正的发送文件到客户端,因此,我们必须启用 static files 中间件(UseStaticFiles)来提供这个默认页面。

通过UseDefaultFile,请求将会默认在文件夹中查找

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

从这个列表中第一个被找到的文件将会被像通过他的完整路径去访问一样的被展现出来(即使浏览器上显示的还是继续显示之前请求的 URII)

下面的代码展示了如何来改变默认显示的文件为 mydefault.html

public void Configure(IApplicationBuilder app)
{
    // 设置网站默认提供浏览的文件
    DefaultFilesOptions options = new DefaultFilesOptions();
    options.DefaultFileNames.Clear();
    options.DefaultFileNames.Add("mydefault.html");
    app.UseDefaultFiles(options);
    app.UseStaticFiles();
}

原文后面的东西我没用上,所以就没有翻译了。。。

posted @ 2016-08-02 14:28  不如隐茶去  阅读(340)  评论(0编辑  收藏  举报