我有一个来自配置的 Azure CDN 端点,我试图将其保存在选项中并注入将使用它的视图中。 我被困住了…… .NET 文档没有显示视图选项注入的标记代码,而且Rick 的帖子似乎没有针对 beta7 进行更新。 我在 dnx-coreclr-win-x64.1.0.0-beta7,这是一个 dnxcore50 应用程序。
(在这里对最佳实践感到困惑:这甚至会出现在模型中吗?)
``` C#
命名空间 MyApp.Models
{
公共类 AppOptions
{
公共字符串 CDN { 获取; 放; }
}
}
#### Startup
``` c#
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var configurationBuilder = new ConfigurationBuilder().AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
Configuration["CDN"] = "az123456";
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AppOptions>(Configuration);
services.AddSingleton(_ => Configuration);
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseErrorHandler("/error");
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
``` C#
公共类 HomeController : 控制器
{
公共主页控制器(IOptions
{
选项 = optionsAccessor.Options;
}
AppOptions Options { get; }
[Route("/error")]
public IActionResult Script() => File("/wwwroot/error.htm", "text/html");
[HttpGet]
public IActionResult Index()
{
return View("index", Options);
}
}
#### Markup
If everything else above is ok, the markup part is unclear to me. How do I inject this?
- as a model with `<strong i="32">@model</strong> MyApp.Models.AppOptions`
- with inject `<strong i="33">@inject</strong> MyApp.Models.AppOptions AppOptions`
- is the problem with the reference in the `src=` ... how do I break the property lookup at the "CDN" before the period prior to "vo"?
``` html
<strong i="34">@inject</strong> MyApp.Models.AppOptions AppOptions
...
<body>
<!-- Error (squiggles) on "AppOptions" and complains it can't be found -->
<img src="http://@{AppOptions.CDN}.vo.msecnd.net/container/image.png" alt="Image from CDN">
<!-- Error (squiggles) on "vo" and complains its trying to lookup "vo" on the property -->
<img src="http://@AppOptions.CDN.vo.msecnd.net/container/image.png" alt="Image from CDN">
</body>
...
...如果我使用<strong i="37">@model</strong> MyApp.Models.AppOptions
和@{Model.CDN}.vo...
或@Model.CDN.vo...
,结果相同。
由于IOptions
是 DI 容器中的那个,因此您需要<strong i="6">@inject</strong> IOptions<AppOptions> AppOptionsAccessor
对于 Razor 曲线,问题在于您使用了错误的括号:
<img src="http://@(AppOptionsAccessor.Options.CDN).vo.msecnd.net/container/image.png" alt="Image from CDN">
@pranavkm啊! 明白了。 谢谢。
对于其他任何人,请记住您必须完全限定要注入的接口。
<strong i="6">@inject</strong> Microsoft.Extensions.Options.IOptions<AppOptions> AppOptionsAccessor
最有用的评论
对于其他任何人,请记住您必须完全限定要注入的接口。
<strong i="6">@inject</strong> Microsoft.Extensions.Options.IOptions<AppOptions> AppOptionsAccessor