问题描述
我有指向剃须刀页面上网络共享目录中文件的链接,我想在appsettings.json文件中对其进行配置,但是我无法找到一种方法来使用cshtml锚标记中的已配置密钥。有没有办法使用razor语法做到这一点?
在此先感谢您的帮助。
解决方法
我假设您已将目录路径存储在appsettings.json文件中,并且想要从appsettings.json文件中获取路径并使用定位标记中的值,对吗?如果是这种情况,您可以尝试使用以下方法来使用“剃刀页面”中的配置。
appsettings.json文件中的“添加文件”节点:
{
"Logging": {
"LogLevel": {
"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
}
},"File": {
"FilePath": "https://docs.microsoft.com/"
},"AllowedHosts": "*"
}
-
在Razor页面(index.cshtml)中使用@inject指令。
@using Microsoft.Extensions.Configuration @inject IConfiguration Configuration <a href="@Configuration.GetSection("File")["FilePath"]">Microsoft</a>
-
使用ViewData或ViewBag存储路径并将其显示在锚标记中。
.cshtml.cs文件中的代码:
public class IndexModel : PageModel { private readonly IConfiguration _configuration; public IndexModel(IConfiguration configuration) { _configuration = configuration; } public void OnGet() { ViewData["config"] = _configuration["File:FilePath"]; //get the configuration key value. } }
视图页面中的代码(.cshtml):
<a href="@ViewData["config"]">Microsoft</a>
结果如下: