webconfig,form验证存角色


网站用户分级的解决方案

普通用户分级
这里一般用cookie,.net里有更加密的算法。
单个页
<location path="EditPost.aspx">
 <system.web>
  <authorization>
                        <allow roles="RoleName" />
   <deny users="?" />
  </authorization>
 </system.web>
    </location>

webconfig.xml所在文件夹

<configuration>
     <system.web>
 <authorization>
           <allow roles="RoleName" />
    <deny users="*" />
 </authorization>
     </system.web>
   </configuration>
  说明:子目录的web.config设置优先于父目录的web.config设置

这是写死的办法

 FormsAuthenticationTicket authTicket = new
 FormsAuthenticationTicket(
            1, // version
            txtUserName.Text, // user name
            DateTime.Now, // creation
            DateTime.Now.AddMinutes(20),// Expiration
            false, // Persistent
            roles ); // User data
  roles是一个角色字符串数组
  string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密

  存入Cookie
  HttpCookie authCookie =
  new HttpCookie(FormsAuthentication.FormsCookieName,
  encryptedTicket);

  Response.Cookies.Add(authCookie);
这里将roles写入cookies,这样上面的EditPost.aspx就可以访问了。

如果是不同角色在同一个页有不同控件显示

HttpCookie authCookie = Context.Request.Cookies

[FormsAuthentication.FormsCookieName];
  FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt

(authCookie.Value);//解密
  string[] roles = authTicket.UserData.Split(new char[]{';'});
这样就可以判断出rolse了

而admin用户就写在session,不用这么麻烦

分级模式
把不能匿名访问的页分类放在文件夹里,文件夹webconfig设好不能匿名访问,返回

login.aspx代码分别是
<configuration>
     <system.web>
 <authorization>
           <allow roles="RoleName" /> //这里按需求可不写
    <deny users="?" />
 </authorization>
     </system.web>
   </configuration>

 <authentication mode="Forms">
        <forms name=".ASPXUSERDEMO" loginUrl="login.aspx" protection="All"

timeout="20" />
      </authentication>
在login.aspxc通过FormsAuthentication.RedirectFromLoginPage("username",true);
转给要访问的页。
所有要验证的页都通过一个basepage.aspx继承而来或者admin页一个basepage,user页
一个basepage,basepage主要处理用户角色,及是用cookie来存还是用session来存。


静态页综合
通过webrequest
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
System.Net.WebResponse wResp =wReq.GetResponse();
System.IO.Stream respStream  = wResp.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(respStream,

System.Text.Encoding.GetEncoding("gb2312"));
再用把如show.aspx?id=11111字符串改为showaspxid11111.html
这种可以用于批量
模版法
用js或直接替代模版相关字符串
自我生成法
可用第一种,也可RenderControl,输出控件html内容。但里面不能有表单控件。
也可用javascrip的document.documentElement.innerHTML; 用隐藏域提交上来。

原文地址:https://www.cnblogs.com/suneryong/p/718149.html