欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.net 基于Cookie简易的权限判断

程序员文章站 2024-03-08 23:37:04
写入cookie页面,创建cookie后,设置cookie属性,并添加到response.cookies中读取cookie,利用cookie的名字或索引从request.c...
写入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;
}
}
}