[英]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.