【问题标题】:Control authentication from basepage从主页控制身份验证
【发布时间】:2012-12-02 21:42:42
【问题描述】:

我想在 asp.net 中控制用户身份验证。

假设; 有两个 web 来自 StackOverflow.aspx 和 Default.aspx。

我想通过以下代码获得经过身份验证的角色:

public List<Roles> GetAuthenticatedRolesByModuleName(string moduleName)
{
    //below I wrote psedeu code
    var roles = "Select * From SiteRoles Where ModuleName = "Admin";
    //...   
}
//This function returns a result set which includes roles authentication for `moduleName` parameter.

我将使用当前登录系统的角色来控制它。

我想在 asp.net 的基本页面中这样做。

为了做到这一点,我创建了一个继承自 System.Web.UI.PageBasePage.cs。 我想将GetAuthenticatedRolesByModuleName 函数写入BasePage.cs,当用户输入StackOverflow.aspx 时,我想从BasePage.cs 调用该函数。

StackOverflow.aspx 有页面加载事件,我想我必须控制Init() 中的角色。

我用谷歌搜索并找到了一些来源,例如:ASP.net "BasePage" class ideas 但我没看清楚。

我想从基本页​​面函数中获取角色(moduleName 是 stack-overflow --> GetAuthenticatedRolesByModuleName(stack-overflow))并使用当前角色进行控制。 如果用户未通过身份验证,我会将其重定向到Default.aspx

Response.Redirect("Default.aspx");

我该怎么做?你能告诉我实现它的方法吗?

【问题讨论】:

  • FormsAuthentication 机制将是正确的选择。
  • 在 stackoverflow.aspx.cs 页面中继承 BasePage.cs,并且您在 BasePage 中放置的每个公共/受保护方法都将在 stackoverflow.aspx 页面中可用。

标签: c# asp.net oop c#-4.0


【解决方案1】:

如果您使用OnpreInitOnInit 制作一个基页以全局检查它,会以某种方式这样:

public abstract class BasePage : System.Web.UI.Page
{
    protected override void OnPreInit(EventArgs e)
    {
        string cTheFile = HttpContext.Current.Request.Path;

        // here select what part of that string you won to check out
        if(!GetAuthenticatedRolesByModuleName(cTheFile))
        {
            // some how avoid the crash if call the same page again
            if(!cTheFile.EndsWith("Default.aspx"))
            {       
                Response.Redirect("Default.aspx", true);
                return ;
            }
        }

        // continue with the rest of the page
        base.OnPreInit(e);
    }
}

但您也可以使用Application_AuthenticateRequestglobal.asax 进行相同的检查:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    // αυτό είναι το path...
    string cTheFile = HttpContext.Current.Request.Path;

    // here select what part of that string you won to check out
    if(!GetAuthenticatedRolesByModuleName(cTheFile))
    {
        // some how avoid the crash if call the same page again
        if(!cTheFile.EndsWith("Default.aspx"))
        {       
            Response.Redirect("Default.aspx", true);
            Response.End();

            return ;
        }
    }
}       

可能需要根据你的代码添加一些细节,但这是大体思路。

【讨论】:

    猜你喜欢
    • 2023-02-24
    • 2016-01-24
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多