我使用dotnet core mvc(v3.0预览版)并使用区域来分隔应用程序的大部分独立页面。我希望将.js和.css文件也存储在area文件夹中,因此我在Startup.cs
中提出了以下要求:
app.UseStaticFiles();// wwwroot
var areas = new string[]{"Intro", "Todo"};
app.UseStaticFiles(new StaticFileOptions{
FileProvider = new CompositeFileProvider( areas.Select( area =>
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(),"Areas", area, "wwwarearoot"))
).ToArray()),
RequestPath = "/areas",
ContentTypeProvider = new FileExtensionContentTypeProvider(
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ ".js", "application/javascript" },
{ ".css", "text/css"},
})
});
这允许(要求)我在文件夹Areas/Intro/wwwarearoot/
和Areas/Todo/wwwarearoot/
中使用js,并在~/areas/
前缀下导入javascript和css。
我的问题i关于如何改进第二行,因此我实际上获得了应用程序领域,而不是拥有静态列表。
答案 0 :(得分:0)
由于搜索此问题时找不到代码,因此这里是我得到的完整代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
namespace MyNamespace.Utils{
public static class AppExtensions{
private static IEnumerable<string> _GetAreasWithAreaRoot(){
var cd = Directory.GetCurrentDirectory();
var directory = new DirectoryInfo(Path.Combine(cd, "Areas"));
var areas = directory.EnumerateDirectories();
foreach(var area in areas){
var wwwarearoot = area.EnumerateDirectories("wwwarearoot").FirstOrDefault();
if(wwwarearoot != null){
yield return wwwarearoot.FullName;
}
}
}
public static void UseAreaStaticFiles(this IApplicationBuilder app){
var areas = _GetAreasWithAreaRoot();
app.UseStaticFiles(new StaticFileOptions{
FileProvider = new CompositeFileProvider( areas.Select( areawwwroot =>
new PhysicalFileProvider(areawwwroot)
).ToArray()),
RequestPath = "/areas",
ContentTypeProvider = new FileExtensionContentTypeProvider(
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ ".js", "application/javascript" },
{ ".css", "text/css"}
})
});
}
}
}
我可以在Startup.cs
中添加
using MyNamespace.Utils;
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseAreaStaticFiles(); // Areas/{area}/wwwarearoot
...
}