Asp.net 基於Cookie簡易的許可權判斷

來源:互聯網
上載者:User

寫入Cookie頁面,建立cookie後,設定cookie屬性,並添加到Response.Cookies中讀取cookie,利用cookie的名字或索引從Request.Cookies中取得改寫Cookie,先建立一個同名的cookie,讀取Request中同名的cookie,把讀取cookie的屬性值付給新的對象,加入到Response.Cookies中建立一個BasePage頁面,其他的頁面繼承自這個頁面,把許可權判斷的代碼有單個頁面的Page_Load轉移到BasePage的PreLoad中,下面是BasePage的主要代碼 複製代碼 代碼如下:public class BasePage : System.Web.UI.Page
{
private string pageName;
public BasePage()
{
this.Page.PreLoad += Page_Load;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Uri r = this.Request.Url;
pageName = r.AbsolutePath;
if (NeedToCheck())
{
if (!HasAuthentication())
{
HttpContext.Current.Response.Redirect("NoAuthenticationPage.aspx");
}
}
}
}
private bool NeedToCheck()
{
if (pageName.Contains("NoAuthenticationPage.aspx") || pageName == "Login.aspx" )
{
return false;
}
return true;
}
private bool HasAuthentication()
{
//look into the config file or database,to see whether this page is in the allow accessing list of the role or not;
//the signature of the function is like this
//QueryInConfig(m_UserRole,pageName);
if (pageName.Contains("Default3.aspx") && UserRole == "2")
{
return false;
}
return true;
}
protected HttpCookie _RequestCookie;
protected HttpCookie _ResponseCookie;
private bool b_IsNewCookie = true;
public string UserRole
{
get
{
return GetCookieValue("UserRole");
}
set
{
SetCookieValue("UserRole", value);
}
}
public string UserName
{
get
{
return GetCookieValue("UserName");
}
set
{
SetCookieValue("UserName", value);
}
}
protected void SetCookieValue(string name, string value)
{
SetResponseCookie();
_ResponseCookie[name] = value;
}
private string GetCookieValue(string name)
{
SetReqeustCookie();
if (_RequestCookie != null)
{
return _RequestCookie[name];
}
return null;
}
protected void SetReqeustCookie()
{
_RequestCookie = HttpContext.Current.Request.Cookies["Cookie_Name"];
}
protected void SetResponseCookie()
{
if (b_IsNewCookie)
{
HttpContext.Current.Response.Cookies.Remove("Cookie_Name");
_ResponseCookie = new HttpCookie("Cookie_Name");
DateTime dtNow = DateTime.Now;
TimeSpan tsMinute = new TimeSpan(0, 2, 0, 0);
_ResponseCookie.Expires = dtNow + tsMinute;
_ResponseCookie["UserRole"] = UserRole;
_ResponseCookie["UserName"] = UserName;
HttpContext.Current.Response.Cookies.Add(_ResponseCookie);
b_IsNewCookie = false;
}
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.