0

我有一个网站,其中有几个从 PageBase 类派生的 aspx 页面。例如其中之一如下:

public partial class Pages_Home_Default : PageBase
{
}

在其中一些页面中,我想阻止访问,除非登录。我可以使用 IsMember 属性在我的 PageBase 中获取客户端是否登录。

我想使用属性来实现这一点。例如:

[AuthenticationRequired(true)]
public partial class Pages_Home_Default : PageBaseList
{
}


[AttributeUsage(AttributeTargets.Class)]
public class AuthenticationRequired : Attribute
{
    public AuthenticationRequired(bool isMemberRequired)
    {
        Value = isMemberRequired;
    }

    public bool Value { get; private set; }
}

例如在 PageBase 中:

protected override void OnPreInit(EventArgs e)
{
    //Retrieve the AuthenticationRequired attribue value and if not authenticated Redirect client to a login page if logged in, continue displaying the page
}

我还发现这个来获取和读取属性

System.Reflection.MemberInfo info = typeof(Pages_Home_Default);
        object[] attributes = info.GetCustomAttributes(true);

但是,当您想在 BASE 类而不是 DERIVED 类上执行此操作时,这是不切实际的。

这可以做到吗?

非常感谢你

4

3 回答 3

2

如果您使用 MVC,则有一个 att - AuthorizeAttribute

如果您使用 WebForms 那么您不需要使用属性,您可以使用授权元素从 web.config 控制它。

于 2012-09-03T08:00:18.913 回答
1

为什么不在属性本身中检查它?

[AttributeUsage(AttributeTargets.Class)]
public class AuthenticationRequired : Attribute
{
    public AuthenticationRequired(bool isMemberRequired)
    {
        if(isMemberRequired && !HttpContext.Current.User.Identity.IsAuthenticated)
        {
          FormsAuthentication.RedirectToLoginPage();
        }
    }
}
于 2012-09-03T08:07:33.353 回答
0

行。我将之前给出的代码与其他来源的简单代码行结合起来,这是我想出的代码:

[AttributeUsage(AttributeTargets.Class)]
public class AuthenticationRequired : Attribute
{
    public AuthenticationRequired(bool isMemberRequired)
    {
        Value = isMemberRequired;
    }

    public bool Value { get; private set; }
}


public class Utility
{
    public static T GetCustomAttribute<T>(Type classType) where T : Attribute
    {
        object Result = null;

        System.Reflection.MemberInfo Info = classType;

        foreach (var Attr in Info.GetCustomAttributes(true))
        {
            if (Attr.GetType() == typeof(T))
            {
                Result = Attr;
                break;
            }
        }
        return (T)Result;
    }
}

public class PageBase : System.Web.UI.Page
{
    protected override void OnPreInit(EventArgs e)
    {
        AuthenticationRequired AttrAuth = Utility.GetCustomAttribute<AuthenticationRequired>(this.GetType());

        if (AttrAuth != null && AttrAuth.Value)
        {
            if(!IsMember)
                HttpContext.Current.Response.Redirect("Membership.aspx");
        }
    }
}
于 2012-09-03T13:35:31.693 回答