我可以在执行操作之前处理请求(使用ActionFilterAttribute或AuthorizeAttribute,以及我认为的其他人)。
如果我需要控制身份验证(识别用户是否已记录)我可以简单地处理前面描述的属性之一并检查我的会话(假设我正在控制使用Session登录)并且如果用户未登录我只是简单重定向到登录页面。
但我怎么能在Asp.net Web Forms中做到这一点?
答案 0 :(得分:0)
执行此操作的一种方法是在页面加载事件中进行检查。在我的情况下,我们使用的是母网页,即网站上每个页面的“共享视图”,因此每个页面加载检查用户是否已登录。
在母版页中我们有:
protected void Page_Load(object sender, EventArgs e)
{
if (!Context.User.Identity.IsAuthenticated)
Response.Redirect("~/Login.aspx");
}
我们正在使用MembershipProvider和FormsAuthentication来跟踪用户
答案 1 :(得分:0)
您可以使所有页面都从基类继承,并在基类中添加逻辑以执行重定向。这最终会在行为上类似于MVC过滤器。
public class BasePage: System.Web.UI.Page
{
public BasePage()
{
this.PreInit += AuthenticationFilter;
}
public void AuthenticationFilter(object sender, EventArgs e)
{
if(!User.IsAuthenticated)
{
Response.Redirect("~/User/Login");
}
}
}
注意,我还没有测试过这段代码。
或者,您可以使用authorization element在web.config
中配置授权。
<configuration>
<system.web>
<authorization>
<allow roles="Admins"/>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
您还可以使用location element选择性地应用授权。