【发布时间】:2022-01-15 01:06:50
【问题描述】:
@Configuration["myKey"] 的这种实现非常适用于不在 @{} 括号之间的代码,但是当我有一个代码块时,它根本不起作用。
据我所知,该文档没有提供任何代码示例...
我该如何解决这个问题?
代码当然在 Razor 页面 (.cshtml) 中。
我尝试删除@ 并在没有@ 的情况下放入相同的代码,但随后它给出了上下文错误...
附:如果重要的话,有问题的代码是 POCO。
P.P.S.我使用@inject IConfiguration Configuration 来导入 Razor 页面顶部的配置。
我有问题的代码:
var website = new WebSite()
{
private string altName = Configuration["FrameworkData:PageTitle"] +" - " +Configuration["FrameworkData:Slogan"];
AlternateName = altName,
....
我已经尝试在配置规范之前指定 IConfiguration 类型,但无济于事。
更新
我的起始代码中包含有问题的部分:
@using Microsoft.AspNetCore.Http;
@using Schema.NET;
@model projectname2.Areas.MyFeature.Pages.Shared._LayoutModel
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@{
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name='description' content='@ViewData["Description"]'>
<title>@ViewData["Title"] - @Configuration["FrameworkData:PageTitle"]</title>
@{
var website = new WebSite()
{
private string altName = "";
string altName = $"{Configuration["FrameworkData:PageTitle"]} - {Configuration["FrameworkData:Slogan"]}";
AlternateName = altName,
Name = Configuration["FrameworkData:PageTitle"],
Url = new Uri("https://example.com")
};
var jsonLd = website.ToString();
var address = new PostalAddress()
{
StreetAddress = "Example street 10",
AddressLocality = "NY",
PostalCode = "11111",
AddressCountry = "US"
};
var geo = new GeoCoordinates()
{
Latitude = 0.3947623,
Longitude = 0.8723408
};
var localbusiness = new LocalBusiness()
{
Name = "Project name",
Image = new Uri("https://example.com/graphics/logo.svg"),
Url = new Uri("https://example.com"),
Telephone = "1234 1243567",
Address = address,
Geo = geo,
SameAs = new Uri("https://example.com"),
OpeningHours = "Mo-Fr 08:00-17:00",
};
var jsonLdlb = localbusiness.ToString();
var organization = new Organization()
{
AreaServed = "US",
ContactPoint = new ContactPoint()
{
AvailableLanguage = "English",
ContactOption = ContactPointOption.TollFree,
ContactType = "customer service",
Telephone = "1234 1243567"
},
Url = new Uri("https://example.com"),
Logo = new Uri("https://example.com/graphics/logo.svg"),
};
var jsonLdorg = organization.ToString();
}
<script type="application/ld+json">
@Html.Raw(jsonLd)
</script>
<script type="application/ld+json">
@Html.Raw(jsonLdlb)
</script>
<script type="application/ld+json">
@Html.Raw(jsonLdorg)
</script>
【问题讨论】:
标签: c# asp.net-core razor