FormsAuthentication.RedirectToLoginPage()不起作用

时间:2012-02-29 21:18:48

标签: c# asp.net

我是ASP.Net的新手。请解释一下我需要添加的内容。 我在登录前单击此页面以通过“FormsAuthentication.RedirectToLoginPage();”将用户带到登录页面。但在Page_Load之后,它转到“dsRequestList_Selecting”。我假设它直接进入Login页面,但是有一些原因它在dsRequestList_Selecting()之后进入登录页面。我需要做什么?

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }

        }
        else
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }
        }
    }

protected void dsRequestList_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
       //Selecting
    }

2 个答案:

答案 0 :(得分:4)

不要这样走。

使用Web.config(或者,对于MVC,[Authorize]属性)来保护页面。您不需要这种代码,并且您不希望它带来错误(在每个页面中)。

你只需要

<configuration>
    <system.web>
       <authorization>
         <deny users="?" /> 
       </authorization>

       ...
    </system.web>

    ....
</configuration>

所有您的网页保护在与此web.config相同的文件夹中。登录表格自动排除。

答案 1 :(得分:1)

尽管已经接受了答案,但我想补充一点来澄清和回答原始问题。

正在执行页面上的其他代码的原因是FormsAuthentication.RedirectToLoginPage()的工作原理。

来自FormsAuthentication.RedirectToLoginPage MSDN

  

与HttpResponse.Redirect方法不同,此方法不会通过调用HttpResponse.End来结束请求。这意味着将运行RedirectToLoginPage方法调用之后的代码。

Henk Holterman所说的是准确的,你不应该在页面本身处理身份验证,或者理想情况下在代码中处理身份验证(重新编译只是为了改变访问权限是愚蠢的)。他发布的web.config示例就足够了。

另外,我会发布一个修改后的代码版本,该代码不允许调用dsRequestList_Selecting,但仍然在页面级别处理身份验证(这也是未经修改的)。

protected void Page_Load(object sender, EventArgs e)
{
    //No need to check IsPostBack if your action is the same either way.
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
        //Note: Using CompleteRequest() over Response.End() is significantly quicker
        //This is because it avoids raising the ThreadAbortException.
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //So if you use CompleteRequest(), you want the return statement after.
        //Unless you wrap the rest of the Page_Load logic in an else statement, like the alternate solution below            
        return;
    }
    //All other Page_Load logic
}

替代,更昂贵的方式(由于例外):

protected void Page_Load(object sender, EventArgs e)
{
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
        Response.End();
    }
    else
    {
        //All other Page_Load logic
    }
}