簡體   English   中英

如何在ASP.NET網頁上使用屬性進行身份驗證?

[英]How to use Attributes for authentications on ASP.NET Webpage?

我有一個網站,該網站具有從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類上執行此操作時,這是不切實際的。

能做到嗎?

非常感謝你

如果你使用MVC,對此有專門的ATT - AuthorizeAttribute

如果您使用的是WebForms,則不需要使用屬性,則可以使用授權元素從web.config中控制該屬性。

為什么不在屬性本身中檢查它?

[AttributeUsage(AttributeTargets.Class)]
public class AuthenticationRequired : Attribute
{
    public AuthenticationRequired(bool isMemberRequired)
    {
        if(isMemberRequired && !HttpContext.Current.User.Identity.IsAuthenticated)
        {
          FormsAuthentication.RedirectToLoginPage();
        }
    }
}

好。 我將前面給出的代碼與其他來源的簡單代碼結合在一起,這是我想到的代碼:

[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");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM