【问题标题】:ASP.NET WebForms - How to Authorise access to a pageASP.NET WebForms - 如何授权对页面的访问
【发布时间】:2015-07-11 04:54:34
【问题描述】:

在最新的 ASP.NET WebForms 应用程序中,我们不再使用 RoleManager 等(据我所知),那么我们如何授权特定角色访问网页?

在 MVC 中,我会使用 Authorize 属性,但在 WebForms 中不存在,所以我不知所措 - 有什么想法吗?

【问题讨论】:

标签: c# asp.net webforms authorization authorize-attribute


【解决方案1】:

研究使用/a web.config 文件和授权元素。为此,您可以在任何目录中创建一个 web.config 文件(即,您可以在整个站点中拥有多个 web.config 文件)。

一个链接(也可以查看其他链接): https://msdn.microsoft.com/en-us/library/8d82143t%28v=vs.85%29.aspx

【讨论】:

    【解决方案2】:

    试试这个代码 在登录时将角色传递给 FormsAuthenticationTicket

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddMinutes(2880), false, role, FormsAuthentication.FormsCookiePath);
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
    
                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }
                Response.Cookies.Add(cookie);
                Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
    

    在特定网络表单上的 Page_Load 事件检索角色

    protected void Page_Load(object sender, EventArgs e)
        {
    
                 FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                 FormsAuthenticationTicket ticket = id.Ticket;
                 string userData = ticket.UserData;
                 string[] temp = userData.Split(',');
                 role=temp[0];
             if (role!="Owner")
             {
                 Response.Write("............");
             }
        }
    

    如果您想在文件夹级别进行授权,那么不要在 webform 上检查角色,而是在该文件夹的 web.config 文件中指定角色

     <authorization>
      <allow  roles="Owner"/>
      <deny users="*"/>
    </authorization>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多