想实现某个目录只允许某类角色访问,点击登陆后IsInRole判断返回true,却总自动返回loginUrl。登陆代码如下:FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "zouwei", DateTime.Now, DateTime.Now.AddHours(24), false, "common", "/");
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
HttpContext.Current.Response.Cookies.Add(userCookie);
HttpContext.Current.Response.Redirect("~/Infos/Homepage.htm", true);
Global.asax代码:protected void Application_AuthorizeRequest(object sender, System.EventArgs e)
{
HttpApplication App = (HttpApplication)sender;
HttpContext Ctx = App.Context;
if (Ctx.Request.IsAuthenticated == true)
{
FormsIdentity Id = (FormsIdentity)Ctx.User.Identity;
FormsAuthenticationTicket Ticket = Id.Ticket;
string[] Roles = Ticket.UserData.Split(',');
Ctx.User = new GenericPrincipal(Id, Roles);
} bool flag = HttpContext.Current.User.IsInRole("common"); //点击登陆按钮后,这里判断角色是true
}
web.config:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="Verse.Web.HttpHandlers.PageHandler, Verse.Web" />
</httpHandlers>
<authorization>
<allow roles="common"/>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
HttpContext.Current.Response.Cookies.Add(userCookie);
HttpContext.Current.Response.Redirect("~/Infos/Homepage.htm", true);
Global.asax代码:protected void Application_AuthorizeRequest(object sender, System.EventArgs e)
{
HttpApplication App = (HttpApplication)sender;
HttpContext Ctx = App.Context;
if (Ctx.Request.IsAuthenticated == true)
{
FormsIdentity Id = (FormsIdentity)Ctx.User.Identity;
FormsAuthenticationTicket Ticket = Id.Ticket;
string[] Roles = Ticket.UserData.Split(',');
Ctx.User = new GenericPrincipal(Id, Roles);
} bool flag = HttpContext.Current.User.IsInRole("common"); //点击登陆按钮后,这里判断角色是true
}
web.config:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="Verse.Web.HttpHandlers.PageHandler, Verse.Web" />
</httpHandlers>
<authorization>
<allow roles="common"/>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpApplication App = (HttpApplication)sender;
HttpContext Ctx = App.Context;
if (Ctx.Request.IsAuthenticated)
{
FormsIdentity Id = Ctx.User.Identity as FormsIdentity;
FormsAuthenticationTicket Ticket = Id.Ticket;
string[] Roles = Ticket.UserData.Split(',');
Ctx.User = new System.Security.Principal.GenericPrincipal(Id, Roles);
}
}