使 ASP.NET 中的某些页面需要登录的最佳方法是什么?
-
20-08-2019 - |
题
我正在开发 asp.net 网站项目,某些页面需要身份验证。我正在使用 asp.net 会员资格。
我读了一些答案。例如将所有这些页面放入文件夹中,并创建描述权限的内部 web.config。这是解决问题的一种方法,但我需要更可修复和更有效的方法。
解决方案
如果您不想在 web.config 中对其进行硬编码,则需要实现“基本页面”类型控件。
您的基页面类应该继承自 System.Web.UI.Page,并且需要有一个可以调用的方法来表示“用户必须登录”或“用户必须处于角色 x”,并且如果用户不是t 在该角色中,重定向到登录页面(您可以通过调用 FormsAuthentication.LoginUrl).
您的实际页面应该从此类继承,而不是直接从 System.Web.UI.Page 继承。然后,在 Init 之类的地方,或者在 Page_Load 的顶部,调用
base.UserMustBeLoggedIn();
或者
// Replace "AccessRole" with the name of your role
base.UserMustBeInRole("AccessRole");
并让基页处理这个问题。
如果您希望将访问权限存储在数据库中,那么您可以将所有处理移至基页,并在页面生命周期中的合适位置,根据数据库表检查当前 URL,检查用户角色/身份验证违反要求并根据需要重定向。
请注意,您可以在 Web 配置中创建页面级安全性,如下所示:
<configuration>
<location path="LockedPage.aspx">
<system.web>
<authorization>
<!-- Deny access to anonymous users -->
<deny users="?"/>
</authorization>
</system.web>
</location>
</configuration>
其他提示
您可以试试这个代码, 在主页加载事件编写此代码, 添加属性
公共BOOL m_bLoginRequired = TRUE;
public bool IsLoginRequired
{
get { return m_bLoginRequired; }
set { m_bLoginRequired = value; }
}
try
{
// Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
Response.Cache.SetNoStore();
if (IsLoginRequired==true)
{
if ( Session.IsNewSession || HttpContext.Current.Session["Username"] == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage("Session Expired");
Response.End();
}
}
}
catch (Exception ex)
{
throw (ex);
}
现在在登录页面,你需要编写此代码
FormsAuthentication.SetAuthCookie(this.txt_UserName.Text.Trim(), false); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.txt_UserName.Text.Trim(), DateTime.Now, DateTime.Now.AddMinutes(10), false, "HR");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Name = "jay";
Session["UserName"] = txt_UserName.Text.Trim();
Response.Cookies.Add(cookie);
txt_UserName.Text = "";
txt_Password.Text = "";
Response.Redirect("HomePage2.aspx");
现在你AVE在登录页面添加pageinit事件
protected void Page_PreInit(object sender, EventArgs e)
{
Master.IsLoginRequired = false;
}
如果您希望用户能够然后访问一个未授权的页面 在该页面的pageinit事件
设置Master.IsLoginRequired=false;
还指定在web.config
文件loginurl。
不隶属于 StackOverflow