在 mvc 视图中获取 web.config 自定义部分中的参数值
Getting value of parameter in web.config custom section in mvc View
我在 web.config 中有用户角色的自定义部分:
<roles>
<add key="Role1" value="Dev" />
<add key="Role2" value="Dev2" />
</roles>
而且我想在我的 _layout 页面中使用键来获取值。然后根据用户包含的角色在菜单中隐藏 link。像这样:
@if (User.IsInRole(@System.Configuration.ConfigurationManager.GetSection("roles")["Role1"]))
{
<li>@Html.ActionLink("{{'Statistics' | translate}}", "Statistics", "Home", new { area = "" }, null)</li>
}
您不能直接访问该值System.Configuration.ConfigurationManager.GetSection("roles")["Role1"].
执行类型转换并访问键的值,如下所示。
var section = ConfigurationManager.GetSection("roles") as NameValueCollection;
var value = section["Role1"];
在 .cshtml/_Layout 页面中,您可以使用 @ 符号,如下所示。
@{
var section = System.Configuration.ConfigurationManager.GetSection("roles") as System.Collections.Specialized.NameValueCollection;
var value = section["Role1"];
}
谢谢巴拉吉 M!
这是我的代码的最终版本:
@{
var sections = System.Configuration.ConfigurationManager.GetSection("roles") as System.Collections.Specialized.NameValueCollection;
}
@if (User.IsInRole(sections["StatistiscRole"]))
{
<li>@Html.ActionLink("{{'Statistics' | translate}}", "Statistics", "Home", new { area = "" }, null)</li>
}
我在 web.config 中有用户角色的自定义部分:
<roles>
<add key="Role1" value="Dev" />
<add key="Role2" value="Dev2" />
</roles>
而且我想在我的 _layout 页面中使用键来获取值。然后根据用户包含的角色在菜单中隐藏 link。像这样:
@if (User.IsInRole(@System.Configuration.ConfigurationManager.GetSection("roles")["Role1"]))
{
<li>@Html.ActionLink("{{'Statistics' | translate}}", "Statistics", "Home", new { area = "" }, null)</li>
}
您不能直接访问该值System.Configuration.ConfigurationManager.GetSection("roles")["Role1"].
执行类型转换并访问键的值,如下所示。
var section = ConfigurationManager.GetSection("roles") as NameValueCollection;
var value = section["Role1"];
在 .cshtml/_Layout 页面中,您可以使用 @ 符号,如下所示。
@{
var section = System.Configuration.ConfigurationManager.GetSection("roles") as System.Collections.Specialized.NameValueCollection;
var value = section["Role1"];
}
谢谢巴拉吉 M! 这是我的代码的最终版本:
@{
var sections = System.Configuration.ConfigurationManager.GetSection("roles") as System.Collections.Specialized.NameValueCollection;
}
@if (User.IsInRole(sections["StatistiscRole"]))
{
<li>@Html.ActionLink("{{'Statistics' | translate}}", "Statistics", "Home", new { area = "" }, null)</li>
}