[英]Asp.net MVC TagHelper not registering
我一直在关注这个博客条目https://blog.maartenballiauw.be/post/2020/04/14/building-an-as.net-core-tag-helper-to-show-hide-ui-elements-based -on-authorization.html制作自定义 TagHelper。
但是,我似乎无法识别 TagHelper。
AuthRolesTagHelper.cs:
using System;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace DHS_Intranet.Helpers
{
[HtmlTargetElement("*", Attributes = "asp-authroles")]
public class AuthRolesTagHelper : TagHelper
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly MyManager<ApplicationUser> _myManager;
public AuthRolesTagHelper(
IHttpContextAccessor httpContextAccessor, MyManager<ApplicationUser> myManager)
{
_httpContextAccessor = httpContextAccessor;
_myManager = myManager;
}
[HtmlAttributeName("asp-authroles")]
public string AuthRoles { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
await base.ProcessAsync(context, output);
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext != null)
{
//Get ApplicationUser from HTTP context
var _user = await _myManager.GetUserAsync(httpContext.User);
// check if user roles are in supplied roles.
if (!(await _myManager.IsInRoleAsync(_user, AuthRoles)))
{
output.SuppressOutput();
}
}
}
}
}
本质上,我想在标签的属性 asp-authroles="ExampleRole" 中提供一个角色,如果用户不在角色中,则 output 将被抑制(基本上隐藏)。
我知道这可以使用 razor 页面中的代码块来实现,但我正在努力简化流程。
我在 _ViewImports.cs 中使用了@addTagHelper *, DHS_Intr.net
DHS_Intr.net
但是,当我使用它时(下面的示例),它无法识别 TagHelper 输出只是输出具有可见属性的 Html。
我什至对 TagHelper 代码进行了代码破解,但它从未被触发。
示例页面:
<div class="">
<h1 class="display-4">Directory</h1>
</div>
<div class="input-group">
<input id="search" type="text" class="form-control rounded" placeholder="Search" />
<a href="/Directory/New" class="btn btn-primary"><i class="bi bi-plus-square-fill"></i></a>
</div>
<div asp-authroles="CanDeleteDirectory">Can delete</div>
非常欢迎任何帮助或建议。
再看一遍,原来在我的 _ViewImports.cs 中我需要:
@addTagHelper *, DHS-Intr.net
而不是@addTagHelper *, DHS_Intr.net
DHS-Intr.net
是应用名称,我想我需要使用命名空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.