Home > Mobile >  Asp.net MVC TagHelper not registering
Asp.net MVC TagHelper not registering

Time:01-17

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 >
    <h1 >Directory</h1>
</div>

<div >
    <input id="search" type="text"  placeholder="Search" />
    <a href="/Directory/New" ><i ></i></a>
</div>
<div asp-authroles="CanDeleteDirectory">Can delete</div>

Any help or suggestions would be really welcome.

CodePudding user response:

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.

  • Related