LoginSignup
11
9

More than 5 years have passed since last update.

ASP.Net Core Identity でログインユーザIDを取得

Last updated at Posted at 2017-03-23

探してもなかなか見つからなかったので自分用メモ。
コントローラクラスの引数に IHttpContextAccessor のインスタンスを渡して httpContextAccessor.HttpContext.User.FindFirst メソッドで探すらしい。あまり理解してません。

戻り値の型は Claim で、 Claim.Value でユーザIDが取得できる。未ログインの時には null が返ってくるのでチェックが必要。

下記のコードはログインしているかどうかチェックして、未ログインの時にはホーム画面にリダイレクト、ログインしているときには何かクエリを実行してビューに渡す例です。一応自分の環境では動作しました。


class SomeController : Controller {

  private readonly Claim _claim;

  // コンストラクタ
  public SomeController(IHttpContextAccessor httpContextAccessor)
  {
    _claim = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
  }

  // GET:
  public async Task<IActionResult> Index()
  {
    if(_claim == null)
    { // ログインしてないときにはホーム画面にリダイレクト
      return RedirectToAction("Index", "Home");
    }

    // ユーザID取得
    string userId = _claim.Value;

    // ユーザIDを使ってクエリとかして...
    var query = // ...

    // ビューに渡す
    return View(await query.ToListAsync());
  }

参考にしたリンク

その他参考

こちらのQAだと Controller.User を使っている。こちらの方がコードがシンプルかも。

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9