2017-11-24 6 views
-2

FindByIdAsync(FindByIdEmailAsync、FindByNameAsyncもこの特定のケースでは機能しません)を使用してユーザーオブジェクトを読み込む際に問題があります。 FindByIdAsyncはnullを返します。ユーザーがデータベース内にあるFindByIdAsyncはヌルのユーザーオブジェクトを返します。ドットネットコア2.0

IdentityController.cs

public class IdentityController : Controller 
{ 
    private readonly UserManager<ApplicationUser> userManager; 
    private readonly IIdentityService identity; 
    private readonly RoleManager<IdentityRole> roleManager; 

    public IdentityController(UserManager<ApplicationUser> userManager, 
           IIdentityService identity, 
           RoleManager<IdentityRole> roleManager) 
    { 
     this.userManager = userManager; 
     this.identity = identity; 
     this.roleManager = roleManager; 
    } 


    public async Task<IActionResult> Roles(string id) 
    { 
     var user = await this.userManager.FindByIdAsync(id); 

     var u = this.userManager.GetUserId(User); 

     if (user == null) 
     { 
      return NotFound(); 
     }  
    .... 

: ​​とユーザーIDは、コントローラのアクションに渡されます。 Debuger

は、新しい標準VS2017 ASPと遊び場のいくつかの並べ替えを試してみました。 NETコアMVCテンプレートを作成し、AboutByIdAsyncのみを追加して動作させます。

おかげ

+1

'' User'は、この行のから来る 'this.userManager.GetUserId(ユーザー)PascalCaseされますか?代わりに 'user'ですか? – CalC

+0

ユーザーはControllerBaseからのcummingです。しかし、この行は問題に関連していない、ちょうどチェックのためにこの方法を取得することができます。問題は、Razorテンプレートのバグのために、パラメータIDが{}で囲まれていることが間違っていたことです。 Dave Cousineauに感謝します。 –

答えて

1

はあなたのイメージによると、あなたのid文字列が{}シンボルに包まれて、まだそれがデータベース内にある文字列ではありません。 GetUserIdから返された値は中括弧で囲まれていません。中括弧をidから解析するか、uの値を使用するか、適切な値をRolesに渡します。

例:

public async Task<IActionResult> Roles(string id) 
{ 
    if (id.Length > 0 && id[0] == '{') 
     id = id.Substring(1, id.Length - 2); 

    var user = await this.userManager.FindByIdAsync(id); 

    var u = this.userManager.GetUserId(User); 

    if (user == null) 
    { 
     return NotFound(); 
    }  
.... 
+0

ありがとうございます!どのような愚かな間違い。不正なRazorテンプレートがパラメータユーザーIDを{}で渡しました。もう一度感謝します。 –

関連する問題