Property not binding when using a custom taghelper in _Layout.cshtml with RazorPages

32 views Asked by At

I have a custom taghelper to conditionally render an HTML element based on authorization policies. However, when passing the string-value containing the policy the property in the taghelper never gets bound and stays null.

What am I doing wrong? Or can't I use a taghelper like this in the layout?

Taghelper

[HtmlTargetElement(Attributes = nameof(Policy))]
public class AuthorizationPolicyTagHelper : TagHelper
{
    private readonly IAuthorizationService authorizationService;
    private readonly IHttpContextAccessor httpContextAccessor;

    public AuthorizationPolicyTagHelper(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor)
    {
        this.authorizationService = authorizationService;
        this.httpContextAccessor = httpContextAccessor;
    }

    public string Policy { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        var user = this.httpContextAccessor.HttpContext.User;
        if (!user.Identity.IsAuthenticated || !(await this.authorizationService.AuthorizeAsync(user, this.Policy)).Succeeded)
        {
            output.SuppressOutput();
        }
    }
}

HTML

<li class="nav-item" policy="@MyConstantString">
    <a asp-page="/Documents/Index" class="nav-link">
        <i class="fas fa-fw fa-file"></i>
        <span>Documents</span>
    </a>
</li>
0

There are 0 answers