网站结构如下:
/default.aspx
/login.aspx
/adminlogin.aspx
/member/*.aspx
/admin/*.aspx
需求:访问/member/路径下的页面的请求转向到/login.aspx;
访问/admin/路径下的页面的请求被转向到/adminlogin.aspx;
一开始,自己假想在/Web.config中作如下配置可以达到目的:
< system.web >
< authentication mode ="Forms" >
< forms loginUrl ="/Login.aspx" name =".ASPXFORMSAUTH" >
</ forms >
</ authentication >
</ system.web >
< location path ="member" >
< system.web >
< authorization >
< deny users ="?" />
</ authorization >
</ system.web >
</ location >
< location path ="admin" >
< system.web >
< authentication mode ="Forms" >
< forms loginUrl ="/AdminLogin.aspx" name =".ASPXFORMSAUTH" >
</ forms >
</ authentication >
< authorization >
< deny users ="?" />
</ authorization >
</ system.web >
</ location >
但很快发现,这样会导致一个运行时错误:
在应用程序级别之外使用注册为 allowDefinition='MachineToApplication' 的节是错误的
Google了几下,遇到同样错误的不少,但问题相似的不多。于是临时采用了一种变通的做法(急于解决问题,可能有良好的/更好的解决方案)。两个步骤:
1. 定义/LoginHandler.ashx。在ProcessRequest方法中,
![]()
if ( ! HttpContext.Current.User.Identity.IsAuthenticated)
{
string loginUrl;
string returnUrl = context.Request.Params["returnUrl"];
if(returnUrl.Contains("/Admin/"))
{
loginUrl = "/AdminLogin.aspx";
}
else
{
loginUrl = "/Public/Login.aspx";
}
if (!string.IsNullOrEmpty(context.Request.Params["returnUrl"]))
{
loginUrl = loginUrl + "?returnUrl=" + HttpUtility.UrlEncode(context.Request.Params["returnUrl"]);
}
context.Response.Redirect(loginUrl);
}
2. 配置/Web.config,
< system.web >
< authentication mode ="Forms" >
< forms loginUrl ="/LoginHandler.ashx" name =".ASPXFORMSAUTH" >
</ forms >
</ authentication >
</ system.web >
< location path ="LoginHandler.ashx" >
< system.web >
< httpHandlers >
< add verb ="*" path ="LoginHandler.ashx" type ="Web.LoginHandler" validate ="true" />
</ httpHandlers >
</ system.web >
</ location >
< location path ="member" >
< system.web >
< authorization >
< deny users ="?" />
</ authorization >
</ system.web >
</ location >
< location path ="admin" >
< system.web >
< authorization >
< deny users ="?" />
</ authorization >
</ system.web >
</ location >