0

PageBase クラスから派生したいくつかの aspx ページを持つ Web サイトがあります。たとえば、その 1 つを以下に示します。

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);

しかし、これは、DERIVED クラスではなく BASE クラスで実行したい場合には実用的ではありません。

これはできますか?

どうもありがとうございました

4

3 に答える 3

2

MVCを使用している場合は、そのためのattがあります-AuthorizeAttribute

WebFormsを使用している場合は、属性を使用する必要はありません。これは、authorization要素を使用して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

Ok。以前に提供したコードを他のソースからの単純な行と組み合わせたところ、思いついたコードは次のとおりです。

[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 に答える