我已經創建了自定義標籤助手來處理這個問題。
[HtmlTargetElement(Attributes = "asp-roles")]
public class SecurityTrimmingTagHelper : TagHelper
{
[ViewContext]
public ViewContext Context { get; set; }
[HtmlAttributeName("asp-roles")]
public string Roles { get; set; }
/// <summary>
/// Hides html element if user is not in provided role.
/// If no role is supplied the html element will be render.
/// </summary>
/// <param name="context"></param>
/// <param name="output"></param>
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!Context.HttpContext.User.Identity.IsAuthenticated)
{
output.SuppressOutput();
}
if (!string.IsNullOrEmpty(Roles))
{
var roles = Roles.Split(',');
foreach (var role in roles)
{
if (!Context.HttpContext.User.IsInRole(role))
{
output.SuppressOutput();
return;
}
}
}
}
}
您可以將其應用於任何html元素。如果你想將它僅適用於特定HTML元素(可以說<li>
)然後改變HtmlTargetElement
到
[HtmlTargetElement("li",Attributes = "asp-roles")]
然後在視圖中,你可以做
<li asp-roles="Admin"><a href="/Profile/Admin">Admin</a></li>