1

我正在使用 ASP.NET 成员资格。如果我所关心的只是我是否有一个非空的 Membership.GetUser(),那么是否有理由使用 Request.IsAuthenticated?

在开发过程中,我无意中创建了 Request.IsAuthenticated 为真,但 Membership.GetUser() 为空的情况,因此我将通过 [Authorize] 过滤测试(全局应用,根据需要专门应用 [AllowAnonymous]),但后来失败了。虽然这种情况在生产中可能不会发生,但我仍然想解释它。

鉴于此,编写一个自定义过滤器是否合适,比如 AuthorizeMembership 或类似的,检查 Membership.GetUser() 而不是 Request.IsAuthenticated?有什么需要注意的问题吗?

如果是这样,是否也可以使用该过滤器来使用我通常需要处理请求的用户属性填充全局 UserInfo 对象?我根本不使用会员资料,而是在单独的应用程序数据库中独立管理我的用户属性。

4

1 回答 1

0

主要区别在于速度。

Request.IsAuthenticatedMembership.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);
        }
    }
}
于 2012-07-04T19:35:04.413 回答