主な違いは速度です。
はRequest.IsAuthenticated
より高速で、内部キャッシュフラグを使用しMembership.GetUser()
ます。
一方が他方よりも速い理由を確認するために、ここにコードを配置します。
public virtual bool IsAuthenticated
{
get
{
if (this.m_isAuthenticated == -1)
{
WindowsPrincipal principal = new WindowsPrincipal(this);
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { 11 });
this.m_isAuthenticated = principal.IsInRole(sid) ? 1 : 0;
}
return (this.m_isAuthenticated == 1);
}
}
しかし、GetUser()
実際にはより多くの情報を提供する必要があるため、呼び出しが多すぎます。
public static MembershipUser GetUser()
{
return GetUser(GetCurrentUserName(), true);
}
private static string GetCurrentUserName()
{
if (HostingEnvironment.IsHosted)
{
HttpContext current = HttpContext.Current;
if (current != null)
{
return current.User.Identity.Name;
}
}
IPrincipal currentPrincipal = Thread.CurrentPrincipal;
if ((currentPrincipal != null) && (currentPrincipal.Identity != null))
{
return currentPrincipal.Identity.Name;
}
return string.Empty;
}
public static MembershipUser GetUser(string username, bool userIsOnline)
{
SecUtility.CheckParameter(ref username, true, false, true, 0, "username");
return Provider.GetUser(username, userIsOnline);
}
internal static void CheckParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName)
{
if (param == null)
{
if (checkForNull)
{
throw new ArgumentNullException(paramName);
}
}
else
{
param = param.Trim();
if (checkIfEmpty && (param.Length < 1))
{
throw new ArgumentException(SR.GetString("Parameter_can_not_be_empty", new object[] { paramName }), paramName);
}
if ((maxSize > 0) && (param.Length > maxSize))
{
throw new ArgumentException(SR.GetString("Parameter_too_long", new object[] { paramName, maxSize.ToString(CultureInfo.InvariantCulture) }), paramName);
}
if (checkForCommas && param.Contains(","))
{
throw new ArgumentException(SR.GetString("Parameter_can_not_contain_comma", new object[] { paramName }), paramName);
}
}
}