为什么我的自定义taghelper会崩溃?

时间:2017-03-16 16:40:12

标签: asp.net-core tag-helpers

在我的Razor View中,我有一个带有taghelper属性的元素:

<td identity-userRole="@user.Id"></td>

这是我的taghelper:

using Hrsa.Core.Generic.Model.Lerd.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;

namespace Hrsa.Core.Web.App.TagHelpers
{
    [HtmlTargetElement("td", Attributes = "identity-userRole")]
    public class UserRolesTagHelper : TagHelper
    {
        private UserManager<AppUser> userManager;
        private RoleManager<IdentityRole> roleManager;

        public UserRolesTagHelper(UserManager<AppUser> usermgr,
            RoleManager<IdentityRole> rolemgr)
        {
            userManager = usermgr;
            roleManager = rolemgr;
        }

        [HtmlAttributeName("identity-userRole")]
        public string User { get; set; }

        public override async void Process(TagHelperContext context,
            TagHelperOutput output)
        {
            List<string> roles = new List<string>();
            AppUser user = await userManager.FindByIdAsync(User);
            if (User != null)
            {
                foreach (var role in await userManager.GetRolesAsync(user))
                {
                    roles.Add(role);
                }
            }

            output.Content.SetContent(roles.Count == 0 ?
                "No Roles" : String.Join(", ", roles));
        }
    }
}

我在_ViewImports.cshtml中注册了这样的内容:

@addTagHelper Hrsa.Core.Web.App.*, Hrsa.Core.Web.App

如果我在构造函数上设置了一个断点,它似乎对每个用户来说都很好。 有一点跳跃,因为它是异步的,但似乎一切都好了。 用户id从HTML中的属性传递,角色已准备好输出到taghelper中Process的末尾。

然后它崩溃了。

如果我通过Cntrl F5,它会说: HTTP ERROR 500。

如果我调试然后在我的第三个用户的第三次点击之后它一直下降到:

output.Content.SetContent(roles.Count == 0 ?
            "No Roles" : String.Join(", ", roles));

然后执行似乎被某个地方吞没了。 它只是挂起。

任何人都可以看到这个问题。

1 个答案:

答案 0 :(得分:0)

我改变了:

public override async void Process(TagHelperContext context,
        TagHelperOutput output)

为:

public override async Task ProcessAsync(TagHelperContext context,
        TagHelperOutput output)