如何在ASP.NET Core 1.1中按控制器/视图读取不同配置键值?
Absolutely! ASP.NET Core's modular configuration system is designed for exactly this kind of flexibility—you can keep your component-specific values in configuration files, no databases or hardcoded constants required. Here's how to replicate your WebForms setup in a clean, maintainable way:
1. Structure Your Configuration Files
Instead of per-folder web.config files, we'll use structured JSON configuration (the default in ASP.NET Core). You have two solid options here:
Option A: Single Structured appsettings.json
Keep all your settings in one file with a hierarchical structure to separate page-specific values from general config:
{ "GeneralSettings": { "ApiUrl": "https://api.example.com", "DefaultTheme": "Light" }, "PageSpecificSettings": { "Page1": { "ProductId": 111 }, "Page2": { "ProductId": 222 }, "Page3": { "ProductId": 333 } } }
Option B: Split into Separate Config Files
If you prefer keeping page settings isolated, create individual JSON files for each page:
appsettings.Page1.jsonappsettings.Page2.jsonappsettings.Page3.json
Each file would contain just its specific value:
// appsettings.Page1.json { "ProductId": 111 }
2. Load Configuration in Startup.cs
Next, wire up these config files in your Startup class so the application can access them.
For Option A (Single Structured File):
public void ConfigureServices(IServiceCollection services) { var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); var configuration = configBuilder.Build(); // Bind the structured settings to a strongly-typed class (see step 3) services.Configure<AppSettings>(configuration); services.AddMvc(); }
For Option B (Separate Files):
You'll load all page-specific files alongside the main config:
public void ConfigureServices(IServiceCollection services) { var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // Load each page config (mark as optional if some might be missing) .AddJsonFile("appsettings.Page1.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.Page2.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.Page3.json", optional: true, reloadOnChange: true); var configuration = configBuilder.Build(); services.AddMvc(); }
3. Use Strongly-Typed Settings (Recommended)
To make accessing settings clean and type-safe, create a configuration class that matches your JSON structure:
public class AppSettings { public GeneralSettings GeneralSettings { get; set; } public Dictionary<string, PageSettings> PageSpecificSettings { get; set; } } public class GeneralSettings { public string ApiUrl { get; set; } public string DefaultTheme { get; set; } } public class PageSettings { public int ProductId { get; set; } }
4. Access Settings in Controllers/Views
Now you can inject the configuration into your controllers and pull the correct ProductId based on the current controller or view context.
In a Controller:
public class Page1Controller : Controller { private readonly AppSettings _appSettings; // Inject the strongly-typed settings via dependency injection public Page1Controller(IOptions<AppSettings> appSettings) { _appSettings = appSettings.Value; } public IActionResult Index() { // Get the current controller name (e.g., "Page1" for Page1Controller) var currentController = ControllerContext.ActionDescriptor.ControllerName; // Fetch the matching ProductId var productId = _appSettings.PageSpecificSettings[currentController].ProductId; // Use productId in your logic ViewBag.ProductId = productId; return View(); } }
In a View:
You can inject the settings directly into views too, if needed:
@inject IOptions<AppSettings> AppSettings @{ // Get the current controller from the view context var currentController = ViewContext.RouteData.Values["controller"].ToString(); var productId = AppSettings.Value.PageSpecificSettings[currentController].ProductId; } <h1>Product ID: @productId</h1>
Bonus: Hot Reload
Notice the reloadOnChange: true parameter when loading JSON files? This means you can edit your config files while the app is running, and the changes will take effect immediately—no need to restart the server, just like the old web.config but more reliable.
内容的提问来源于stack exchange,提问作者Dario

