确定基于路由或域的静态文件 ASP.NET 核心 SPA



是否可以根据 ASP.NET Core 2/3 +中的路由返回不同的静态文件?

例如:

app.domain.com将为公共SPA(ReactJS/VueJS(提供一些index.html

admin.domain.com将为经过身份验证的专用 SPA(角度(呈现一些其他index.html

www.domain.com将为公共着陆页呈现第三个index.html

我在文档中找不到如何 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.0

您可以随时尝试自定义文件提供程序:

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions<StaticFileOptions>()
.Configure<IHttpContextAccessor, IWebHostEnvironment>(
delegate(StaticFileOptions options, IHttpContextAccessor httpContext, IWebHostEnvironment env)
{
options.FileProvider = new ClientAppFileProvider (httpContext, env);
}
);
}
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
}
public class ClientAppFileProvider : IFileProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IWebHostEnvironment _env;
public ClientAppFileProvider(IHttpContextAccessor httpContextAccessor, IWebHostEnvironment env)
{
_httpContextAccessor = httpContextAccessor;
_env = env;
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
return _env.WebRootFileProvider.GetDirectoryContents(subpath); ;
} // End Function GetDirectoryContents 

public IFileInfo GetFileInfo(string subpath)
{
string host = _httpContextAccessor.HttpContext.Request.Host.Host;
if (host.Equals("app.domain.com"))
{
subpath = Path.Combine("app", subpath);
}
else if (host.Equals("admin.domain.com"))
{
subpath = Path.Combine("admin", subpath);
}
else if (host.Equals("www.domain.com"))
{
subpath = Path.Combine("www", subpath);
}
// return _env.ContentRootFileProvider.GetFileInfo(subpath);
return _env.WebRootFileProvider.GetFileInfo(subpath);
}

public IChangeToken Watch(string filter)
{
return _env.WebRootFileProvider.Watch(filter);
} // End Function Watch 

}

要根据域返回不同的内容,您可以尝试更改UseStaticFiles中的内容,例如

app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = async ctx =>
{
var request = ctx.Context.Request;
string index = "";
if (request.Host.Host.Equals("app.domain.com") && request.Path.Value.Contains("index.html"))
{
index = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot", "PublicIndex.html");
}
else if (request.Host.Host.Equals("admin.domain.com") && request.Path.Value.Contains("index.html"))
{
index = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot", "PrivateIndex.html");
}
if (!String.IsNullOrEmpty(index))
{
var fileBytes = File.ReadAllBytes(index);
ctx.Context.Response.ContentLength = fileBytes.Length;
using (var stream = ctx.Context.Response.Body)
{
await stream.WriteAsync(fileBytes, 0, fileBytes.Length);
await stream.FlushAsync();
}
}
}
});

确保wwwroot文件夹中有默认索引.html。

最新更新