ASP.NET Core新手求助:如何保护配置文件?能否使用App_Data文件夹?
Hey there! Let's tackle your two questions step by step—they're super common for folks new to ASP.NET Core, so great call asking about them.
1. 如何保护data/settings.json不被HTTP请求获取?
First off, ASP.NET Core's default behavior helps here: it only serves static files from the wwwroot folder by default. So if your data folder is located outside of wwwroot, users can't access it via HTTP requests like http://10.1.15/data/settings.json—that's the easiest and most secure approach.
If for some reason you have to keep the data folder inside wwwroot, you can lock down access with these methods:
Block JSON files entirely from static file serving:
Configure the static files middleware to exclude JSON files. Add this to yourProgram.cs:var provider = new FileExtensionContentTypeProvider(); // Remove JSON from the list of served file types provider.Mappings.Remove(".json"); app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });Target the specific settings.json file directly:
If you only want to block that one file (and serve other JSONs), use theOnPrepareResponsecallback to intercept requests for it:app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { if (ctx.File.PhysicalPath.EndsWith("settings.json", StringComparison.OrdinalIgnoreCase)) { // Return 404 to hide the file exists ctx.Context.Response.StatusCode = StatusCodes.Status404NotFound; ctx.Context.Response.ContentLength = 0; ctx.Context.Response.Body = Stream.Null; } } });Use the built-in configuration system:
Instead of letting the file sit exposed (even if protected), load it into your app's configuration directly. InProgram.cs:builder.Configuration.AddJsonFile("data/settings.json", optional: true, reloadOnChange: true);This way, your app can read the config values, but the file itself is never exposed via HTTP.
2. ASP.NET Core中能否使用App_Data文件夹?
Absolutely! ASP.NET Core doesn't enforce strict folder structures like ASP.NET Framework did—you can create and use an App_Data folder just like you're used to. Here's what to keep in mind:
- Security benefit: Since
App_Datawon't be insidewwwroot(unless you intentionally put it there), it's automatically protected from HTTP access—perfect for storing sensitive config files or data. - Accessing files in App_Data: To get the correct physical path to files in the folder, use this code:
var settingsPath = Path.Combine(AppContext.BaseDirectory, "App_Data", "settings.json"); - Permissions: Make sure the app has the right permissions to read (and write, if needed) files in
App_Data. For IIS, grant read/write access to the app pool identity; for Linux/macOS, set appropriate file system permissions for the user running the app.
内容的提问来源于stack exchange,提问作者barteloma

