示例代码:
在 Startup.cs 文件的 ConfigureServices 方法中添加以下代码:
services.AddSingleton
在需要修改配置项的地方,注入 MySettings 对象,例如在控制器中:
public class MyController : Controller { private readonly MySettings _mySettings;
public MyController(IOptions options)
{
_mySettings = options.Value;
}
public IActionResult Index()
{
var url = HttpContext.Request.Host.Value;
if (url.Contains("example.com"))
{
_mySettings.SomeSetting = "new value";
}
return View(_mySettings);
}
}
其中 MySettings 为自定义的配置项类。在 appsettings.json 中添加配置项:
{ "MySettings": { "SomeSetting": "default value" } }
当请求的地址包含 example.com 时,修改 MySettings.SomeSetting 的值,否则使用默认值。