2017-03-16 45 views
0

在我的Razor視圖我有我的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 

如果我在構造函數上放置了一個斷點,它似乎對每個用戶來說都是非常棒的。 有一點點跳躍,因爲它是異步的,但一切似乎都建立好了。 用戶標識是從HTML中的屬性傳遞的,並且角色已準備好輸出到標籤幫助程序的結尾處。

但後來它崩潰。

如果我通過CNTRL F5運行,它說: HTTP錯誤500

如果我三分命中爲我的第三個用戶後調試然後它一路下跌到:

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

然後執行似乎被吞噬了某處。 它只是掛起。

任何人都可以看到這個錯誤。

+0

好像也許你的代碼混合用戶和用戶,檢查用戶是否是用它來獲得用戶 –

+0

用戶後空是一個字符串屬性並且用td屬性填充UserId: 轉到:「[HtmlAttributeName(」identity-userRole「)] public string User {get; set; }」。 小寫用戶是一個本地聲明的AppUser:IdentityUser,覆蓋了TagHelper的Process。 – Sam

+0

正確,但是爲什麼在你已經使用它之後檢查用戶是否爲空,在使用它之前應該檢查並且好像你應該檢查用戶在嘗試檢索它之後是否爲空,而是你檢查用戶然後 –

回答

0

我改變:

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

到:

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