zoukankan      html  css  js  c++  java
  • 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(), @"wwwrootimages")),
        RequestPath = new PathString("/MyImages")
    });
    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), @"wwwrootimages")),
            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();
    }
    

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

  • 相关阅读:
    python scrapy爬取前程无忧招聘信息
    scrf 原理及flask-wtf防护
    Django 惰性机制
    Django 中配置MySQL数据库
    Django的安装命令
    python装饰器
    python面向对象之继承
    OSI七层模型
    面向对象
    python函数
  • 原文地址:https://www.cnblogs.com/JacZhu/p/5729157.html
Copyright © 2011-2022 走看看