Skip to main content
 首页 » 编程设计

c#之WebForms 中的方法属性

2024年01月24日26dflying

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

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

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

例如:期望。其中 Secure 是方法属性:

[Secure] 
    protected override void OnInit(EventArgs e) 
    { 
        base.OnInit(e); 
        //Do stuff 
    } 

我该如何着手创建这样的方法属性?如果那不可能,你会建议我怎么做?我有很多用户控件需要在 page_load 或 oninit 上使用它,我正在寻找一种更好的方法来实现它。

请您参考如下方法:

声明你的属性

[AttributeUsage(AttributeTargets.Class)] 
public class SecureAttribute: Attribute 
{              
} 

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

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

从 PageBase 继承所有表单

[Secure] 
public partial class Profile: PageBase 
{ 
 
} 

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