我最近向 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>
最佳答案
根据对 Rob 回答的评论...
"So technically, I need all pages blocked except for default, login and registration pages."
您可以将 AuthorizeAttribute
添加到 GlobalFilterCollection这是应用于 Controller 上所有操作的过滤器集合。然后,在您的 Controller 或操作上,您可以将 [AllowAnonymous]
添加到您希望任何人访问的特定 Controller 或操作中。请参阅下面的示例。
在 App_Start 文件夹中创建一个名为 FIlterConfig.cs 的文件
如果已经存在,只需添加以下行:filters.Add(new AuthorizeAttribute());
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
}
这将要求每个 Controller 和操作默认使用授权。
您可以通过将以下内容添加到您的操作或 Controller 中来使 Controller 或操作未经授权。
[AllowAnonymous]
public class MyController
{
public ActionResult MyAction()
{
return View();
}
}
该 Controller 中的所有操作都将可用。
或
public class MyController
{
[AllowAnonymous]
public ActionResult MyAction()
{
return View();
}
}
只有 Controller 上的操作才可用。
关于asp.net - Application_AuthenticateRequest无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17152891/