更好的选择是从config中读取扩展名/ mime类型对,并将其注入到Config方法中,这样可以从配置中管理扩展名:
appsettings.json
:
"StaticFilesConfig": {
"AllowedExtensions": {
".apk": "application/vnd.android.package-archive",
".ext": "application/ext-example-mimetype" // example
}
}
Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
....
services.Configure<StaticFilesConfig>(Configuration.GetSection("StaticFilesConfig"));
....
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env
, ILoggerFactory loggerFactory, IOptions<StaticFilesConfig> staticFilesConfig)
{
...
if (staticFilesConfig != null)
{
SetStaticFileOptions(app, staticFilesConfig);
}
...
}
private void SetStaticFileOptions(IApplicationBuilder app
, IOptions<StaticFilesConfig> staticFilesOptions)
{
var mapping = staticFilesOptions.Value.AllowedExtensions;
if (mapping != null && mapping.Any())
{
var provider =
new FileExtensionContentTypeProvider(staticFilesOptions.Value.AllowedExtensions);
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});
}
}
}
StaticFilesConfig.cs
:
public class StaticFilesConfig
{
public IDictionary<string, string> AllowedExtensions { get; set; }
}
转载至:https://serverfault.com/questions/501562/configure-iis-7-0-to-download-apk/1006056#1006056