1, 在配置文件 appsettings.JSON 里新增 AppSettings 节点
- {
- "Logging": {
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "AppSettings": {
- "HttpUrl": "http://www.ehongcn.com",
- "Copyright": "山南远宏科技有限公司"
- },
- "AllowedHosts": "*"
- }
2, 新建实体类 AppSettings, 通常建在公共类库 Common 里
- public class AppSettings
- {
- public string HttpUrl { get; set; }
- public string Copyright { get; set; }
- }
3, 在 Startup 类里的 ConfigureServices 配置
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
4, 控制器或者业务类里使用
- private readonly AppSettings _appSettings;
- public HomeController(IOptions<AppSettings> appSettings)
- {
- _appSettings = appSettings.Value;
- }
- public IActionResult Index()
- {
- ViewData["Url"] = _appSettings.HttpUrl;
- return View();
- }
5, 页面上使用
- @using Microsoft.Extensions.Options;
- @using Demo.Common
- @inject IOptions<AppSettings> Settings
- @{
- ViewData["Title"] = "Privacy Policy";
- }
- <h1>@ViewData["Title"]</h1>
- <p > 版权所属有 @Settings.Value.Copyright.</p>
来源: http://www.bubuko.com/infodetail-3041287.html