我最近将基于表单的身份验证添加到 MVC 3 项目中。我的 Application_AuthenticateRequest 函数(Global.asax.cs 文件)和我的 Web.Config 文件设置之间似乎存在问题,因为我的 Application_AuthenticateRequest 函数似乎被无限调用。如何更改我的配置以使其正常工作,如何允许用户访问登录页面和默认页面,同时仍拒绝访问其他页面?
//Global.asax.cs
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}
string[] roles = authTicket.UserData.Split('|');
// Create an Identity object
FormsIdentity id = new FormsIdentity(authTicket);
// This principal will flow throughout the request.
UserPrincipal principal = new UserPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
Thread.CurrentPrincipal = principal;
}
//Web.Config
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn"
protection="All"
cookieless="UseCookies"
slidingExpiration="false"
timeout="30" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*"/>
</authorization>