c# - 在 _Layout 中注入(inject) IOptions<T> 的最佳方法是什么

标签 c# asp.net-core .net-core razor-pages

我使用 ASP.NET Core Razor Pages 构建了一个小型 Web 应用程序,但我想使用 IOptions<T>app.json 传递设置在 _Layout . 谢谢!

最佳答案

您可以使用 @inject将服务注入(inject) Razor View 的 Razor 指令。当然,这也包括选项。所以如果你有一些MyOptions您配置的类(例如在 Startup 类中使用 services.Configure<MyOptions>(options => { … })),然后您可以将选项注入(inject) .cshtml :

@inject IOptions<MyOptions> myOptions

<h1>@myOptions.Value.ApplicationTitle</h1>
<p>@myOptions.Value.ApplicationIntroText</p>

为了避免必须访问 myOptions.Value始终明确地,您还可以使用代码块并将结果首先存储在局部变量中:

@inject IOptions<MyOptions> myOptions
@{
    var opts = myOptions.Value;
}

<h1>@opts.ApplicationTitle</h1>
<p>@opts.ApplicationIntroText</p>

关于c# - 在 _Layout 中注入(inject) IOptions<T> 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52081007/

相关文章:

c# - .Net 5 DateTime.ParseExact 问题

c# - .NET Core 平台中Log4Net Layout.XmlLayout 不创建日志

c# - 如何避免使用 DynamicProxy::CreateClassProxyWithTarget 双重构建代理?

c# - Azure AD 应用程序身份验证在没有委派/白名单权限的情况下成功验证了同一租户中的所有应用程序

asp.net-core - 使用 ASP.NET Core 2.1 本地化页面名称

c# - 访问 ASP.NET Core 2.2 类库中的 HttpContext

c# - EF Core 2.0 使用 where 条件时不加载相关实体

c# - 使用泛型访问基抽象类方法中的子类对象

c# - HitTest 属性

c# - 在正则表达式中使用捷克字符