I have been following this blog entry https://blog.maartenballiauw.be/post/2020/04/14/building-an-aspnet-core-tag-helper-to-show-hide-ui-elements-based-on-authorization.html to make a custom TagHelper.
However, I can't seem to get the TagHelper to be recognised.
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();
}
}
}
}
}
Essentially, I want to supply a role in an attribute asp-authroles="ExampleRole" in a tag and if the user is not in the role for the output to be suppressed (essentially hidden).
I know that this is possible using code blocks within the razor page, but I'm trying to keep things streamlined.
I have used @addTagHelper *, DHS_Intranet
in the _ViewImports.cs
However when I use it (example below), it doesn't recognised the TagHelper out just outputs the Html with the attribute visible.
I've even dropped a codebreak on the TagHelper code and it never gets triggered.
Example page:
<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>
Any help or suggestions would be really welcome.
Looking again, it turns out that in my _ViewImports.cs I needed:
@addTagHelper *, DHS-Intranet
rather than @addTagHelper *, DHS_Intranet
DHS-Intranet
is the app name, I thought I needed the use the namespace.