リクエストを行ったユーザーのIDを取得する必要があります。以前のバージョンのIdentityでは、次のように実行できました。
User.Identity.GetUserId();
しかし、それはもう利用できないようです。
次のようなものもあります:
User.GetUserId();
ただし、User.Identity.IsAuthenticatedがtrueで、User.Identity.Nameが正しく設定されている場合でも、常にnullを返します。
私はそれをするために何を使うべきですか?
編集:私の認証ロジックは [デフォルトのVisual Studio 2015テンプレート] に基づいています。IDはこれまであまり変更されていなかったので、どのように行われているかを確認したい場合は、簡単に確認できます。 githubリンクに貼り付けました。
議論の結果、ユーザーIDにUser.GetUserId()で使用される正しいクレームが含まれていないようです。
NameIdentifierクレームを手動で設定する方法は次のとおりです。
// ClaimsIdentity identity = new ClaimsIdentity...
identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);
以前のバージョンにはそのための組み込みの拡張メソッドがあったと思いますが、彼らはそれを削除しました。あなたはそれを置き換えるためにあなた自身を実装することができます:
using System;
using System.Security.Claims;
using Microsoft.AspNet.Identity;
namespace cloudscribe.Core.Identity
{
public static class ClaimsPrincipalExtensions
{
public static string GetUserId(this ClaimsPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
var claim = principal.FindFirst(ClaimTypes.NameIdentifier);
return claim != null ? claim.Value : null;
}
}
}
ClaimType.NameIdentifierはユーザーIDにマップする必要があります
@ジョーオーデット
他の場所に移動されたことがわかりました。
User.GetUserId => UserManager.GetUserId(User)
User.GetUserName => UserManager.GetUserName(User)
User.IsSignedIn => SignInManager.IsSignedIn(User)
私の目標は、カスタムミドルウェアでUserIdを取得することでした。これは、私が使用したものです。
httpContext.User.Identity.IsAuthenticated ?
httpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value
: Guid.Empty.ToString()