2016-09-21 28 views
0

I一部のページでレンダリングサイドバーにViewComponentを使用します。私はいくつかのアクションのための現在のログインユーザーが必要です、どのようにViewComponentでユーザーを得ることができますか?もちろん、私はビューからInvokeAsyncメソッドにパラメータとして渡すことができますが、私はより良い方法を探しています。ViewComponentの現在のログインユーザーを取得する方法Asp.Netコア

public class SideBarViewComponent : ViewComponent 
{ 
    private readonly UserManager<User> _userManager; 

    public ProfileSideBarViewComponent(UserManager<User> userManager) 
    { 
     _userManager = userManager; 
    } 

    public async Task<IViewComponentResult> InvokeAsync() 
    { 
     //How access User 

     _userManager.GetUserId(User); 

     return View(); 
    } 
} 

答えて

1

は、 ViewComponent:

public abstract class ViewComponent 
{ 
    public ClaimsPrincipal UserClaimsPrincipal { get; } 
    .... 
} 

コントローラ内:

[Controller] 
public abstract class ControllerBase 
{ 
    protected ControllerBase(); 

    public ClaimsPrincipal User { get; } 

    .... 
} 
2

あなたがget or set the Current Userをすることができ、そこからさて、あなたは、現在のHttpContextへのアクセス権を持っています。

ここにいくつかの擬似コードです:

var user = this.HttpContext.User; 
1

あなたはこのようにそれを得ることができるので、あなたがリクエストへのアクセス権を持っている:ViewComponentできるユーザーUserClaimsPrincipalの代わりに、ユーザー

では

public async Task<IViewComponentResult> InvokeAsync() 
{ 
    _userManager.GetUserId(Request.HttpContext.User); 

    return View(); 
} 
関連する問題