技术思绪摘录旅行笔记
静态文件就是web服务器允许直接访问或者下载的文件,一般常用的有javascript文件、css文件、image图片、其他下载的文档或者文件等,本文主要介绍一下.netCore中,如何操作和使用静态文件。

1、提供静态文件:

    .NETCORE中,静态文件不可以被直接访问,而是需要放到wwwroot文件夹下

    默认 Web 应用模板在 Startup.Configure 中调用 UseStaticFiles 方法,这就允许提供静态文件

    默认wwwroot文件夹为Web根目录,这点概念和.Net 4.x里面的MVC不一样

app.UseStaticFiles();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();

    app.UseStaticFiles();//映射到wwwroot文件夹

    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}

无参数 UseStaticFiles 方法重载将 Web根目录中的文件标记为可访问

例:访问这个文件的话/wwwroot/images/MyImage.jpg

<img src="~/images/MyImage.jpg" class="img" alt="My image" />

在上面的代码中,~/就代表的wwwroot(web根目录)


2、提供web根目录之外的文件

    假设我的静态文件放在其他文件夹里,文件夹不叫wwwroot,该怎么办呢?

    ┌──wwwroot

    │    ├─css

    │    ├─images

    │    └─js

    ├──MyStaticFiles

    │    ├─images  

    │    │   ├─red-rose.jpg

    比如以上这个目录结构,我要访问red-rose.jpg文件

    app.UseStaticFiles(); //这句需要改下

// using Microsoft.Extensions.FileProviders;
// using System.IO;
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "MyStaticFiles")),
    RequestPath = "/StaticFiles" //指定一个路径前缀名称 不必须
});

在前面的代码中,MyStaticFiles 目录层次结构通过 StaticFiles URI 段公开 。

例:访问/MyStaticFiles/images/red-rose.jpg

<img src="~/StaticFiles/images/red-rose.jpg" class="img" alt="A red rose" />

这时候~/不再代表wwwroot,代表的是MyStaticFiles文件夹


3、利用外部文件访问的逻辑,来提供文件授权

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();

    // wwwroot css, JavaScript, and images don't require authentication.
    app.UseStaticFiles();   

    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "MyStaticFiles")),
        RequestPath = "/StaticFiles"
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

以上代码中,UseStaticFiles方法出现了两次,第一次在授权之前,第二次在授权之后,并指定了新的目录,新的目录将在授权后才能访问

还有一种方式就是将文件访问封装到需要授权的方法中

[Authorize]
public IActionResult BannerImage()
{
    var filePath = Path.Combine(_env.ContentRootPath, "MyStaticFiles", "images", "red-rose.jpg");
    return PhysicalFile(filePath, "image/jpeg");
}


4、FileExtensionContentTypeProvider类使用,包含 Mappings 属性,用作文件扩展名到 MIME 内容类型的映射

      在以下示例中,多个文件扩展名映射到了已知的 MIME 类型。 替换了 .rtf 扩展名,删除了 .mp4

// using Microsoft.AspNetCore.StaticFiles;
// using Microsoft.Extensions.FileProviders;
// using System.IO;

// Set up custom content types - associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, "images")),
    RequestPath = "/MyImages",
    ContentTypeProvider = provider
});

项目中,遇到下载apk文件的时候,不允许,就需要配置一下

app.UseStaticFiles(new StaticFileOptions
    {
           //FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
           //设置不限制content-type 该设置可以下载所有类型的文件,但是不建议这么设置,因为不安全
           //下面设置可以下载apk类型的文件
           ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary{
                    { ".apk", "application/vnd.android.package-archive" }
            })
     });

ContentType可以查询我的另一篇文章:HTTP content-type

CarsonIT 微信扫码关注公众号 策略、创意、技术

留下您的脚步

 

最近评论

查看更多>>

站点统计

总文章数:275 总分类数:18 总评论数:88 总浏览数:124.79万

精选推荐

阅读排行

友情打赏

请打开您的微信,扫一扫