你在卡梅伦的回答下的评论让我有点困惑,所以我的回答可能不是你想做的。
无论如何,您可以使用app.UseStaticFiles()添加中间件来保护该文件夹。由于它是中间件,因此您需要将其插入管道中的正确位置才能使其工作。这是完整的Configure方法Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
// Notice that this is the second time we're calling UseStaticFiles().
// The first call is to configure CSS and things to be served.
// This is deliberately called after UseAuthentication().
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
if (ctx.Context.Request.Path.StartsWithSegments("/keys"))
{
// As the files are sensitive, don't cache a response.
ctx.Context.Response.Headers.Add("Cache-Control", "no-store");
if (!ctx.Context.User.Identity.IsAuthenticated)
{
ctx.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
ctx.Context.Response.ContentLength = 0;
ctx.Context.Response.Body = Stream.Null;
}
}
},
// It's the combination of the `FileProvider` and `RequestPath` that
// maps the `MyKeys` physical folder to the `/keys` path.
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "MyKeys")),
RequestPath = "/keys"
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
在上面的示例中,MyKeys是项目根目录下的文件夹,并且/keys是用于请求文件的路径:
ProjectName
| wwwroot
| css
| etc
| Pages
| your razor pages
| MyKeys
| clear.txt
如果用户未通过身份验证,他们将收到 401 响应。我们故意不缓存结果,因为文件很敏感。当然,您可以在这里做更多的事情,例如要求用户具有特定角色,或者如果他们没有登录则重定向他们。这取决于您。