WebForms中的方法属性

xoa*_*ail 1 c# asp.net webforms

将安全逻辑分配给ASP.NET WebForms中的方法的最佳方法是什么?在什么地方可以使用方法属性,而不是在每个方法下都检查用户是否已登录?示例,而不是这样做:

protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (!UserLoggedIn)
        {
            Response.Redirect("/login");
        }
        //Do stuff
    }
Run Code Online (Sandbox Code Playgroud)

我想做下面的事情。我已经在ASP.NET MVC应用程序中看到它完成了,但是我想知道是否可以使用Webforms实现它。另外,确保只有经过身份验证的用户可以继续并且其他人重定向到登录页面的最佳实践是什么?

例如:需要。其中Secure是方法属性:

[Secure]
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //Do stuff
    }
Run Code Online (Sandbox Code Playgroud)

我该如何创建这种方法属性?如果那不可能,那么您将如何推荐我呢?我在page_load或oninit上有许多需要此功能的用户控件,我正在寻找一种更好的方法来实现。

Gen*_*ady 5

声明您的属性

[AttributeUsage(AttributeTargets.Class)]
public class SecureAttribute: Attribute
{             
}
Run Code Online (Sandbox Code Playgroud)

为所有表单创建自定义基页类

public class PageBase: Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        var secureAttr = Attribute.GetCustomAttribute(this.GetType(), typeof (SecureAttribute));
        if (secureAttr != null)
        {
            bool UserLoggedIn = false; // get actual state from DB or Session

            if (!UserLoggedIn)
            {
                Response.Redirect("/login");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

从PageBase继承所有表单

[Secure]
public partial class Profile: PageBase
{

}
Run Code Online (Sandbox Code Playgroud)

为用户控件创建类似的UserControlBase。