ASP.NET Core Static Files

以前写的文章和参考

Asp.net core 学习笔记 ( IIS, static file 性能优化 )

官网

 

正文

通常 static files 会带上 zip, cache, minify

zip 和 cache ASP.NET Core 都有 build-in 的, JS, CSS minify 用 Webpack, HTML 用 WebMarkupMin

public static class MiniCompressionCacheServiceCollectionExtensions
{
    public static IServiceCollection AddMiniCompressionCache(this IServiceCollection services)
    {
        services.AddResponseCompression(options =>
        {
            options.EnableForHttps = true;
        });

        var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();
        fileExtensionContentTypeProvider.Mappings[".webmanifest"] = "application/manifest+json";
        services.Configure<StaticFileOptions>(options =>
        {
            options.ContentTypeProvider = fileExtensionContentTypeProvider;
            options.OnPrepareResponse = ctx =>
            {
                var cachePeriod = TimeSpan.FromDays(365 * 15).TotalSeconds.ToString();
                ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
            };
        });

        services.AddWebMarkupMin().AddHtmlMinification();
        return services;
    }
}

startup.cs > ConfigureServices

services.AddMiniCompressionCache();

startup.cs > Configure

app.UseStaticFiles();

这样就可以了.

 

处理没有 extension 的 files

参考:

ASP.NET Core 2.0 - Serving files with no extension

How can you use multiple directories for static files in an aspnet core app?

这个需求有点奇葩哦. 我是因为用 face-api.js, 它的 models files 是没有 extension 的...

解决方法是在 startup.cs > Configure 加多一个 UseStaticFiles, 然后指定路径来特别处理. ServeUnknownFileTypes 是有安全隐患的, 所以要小心用哦.

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/face-api-models")),
    RequestPath = "/face-api-models",
    ServeUnknownFileTypes = true,
});

 

上一篇:解决跨域问题前端同源政策被限制


下一篇:添加google 三件套(不root 不刷机)