Application_AuthenticateRequest 上的 ASP.NET MVC 重定向困境
我希望我的 MVC 应用程序检查(针对每个请求)当前用户是否有配置文件。如果没有找到个人资料,我想将他们重定向到“个人资料”页面,以便他们提交一份个人资料。
protected void Application_AuthenticateRequest()
{
if (HttpContext.Current.User != null)
{
// Redirect to profile page if the current user does not have a profile
if (!HttpContext.Current.User.HasProfile())
Response.RedirectToRoute("Profile");
}
}
我已经扩展了 IPrincipal 以包含方法“User.HasProfile()”来检查用户是否有配置文件。它有效,但问题是 Application_AuthenticateRequest 会为每个请求调用,包括 javascript、css 等...
此外,当我尝试执行 Response.RedirectToRoute("Profile ”)。
我发现解决这个问题的唯一方法是在重定向到配置文件页面之前将以下内容添加到我的 IF 语句中:
!HttpContext.Current.User.HasProfile() && Request.Path != "/system/profile" && !Request.Path.Contains(".")
它检查当前路径是否不是配置文件页面(以防止重定向循环)以及URL(允许 javascript 和 css 资源继续加载)。 有更好的方法吗?你们如何处理这个问题?
I would like my MVC application to check (on every request) if the current user has a profile. If no profile is found, I want to redirect them to the "profile" page for them to submit one.
protected void Application_AuthenticateRequest()
{
if (HttpContext.Current.User != null)
{
// Redirect to profile page if the current user does not have a profile
if (!HttpContext.Current.User.HasProfile())
Response.RedirectToRoute("Profile");
}
}
I have extended the IPrincipal to include a method "User.HasProfile()" to check if the user has a profile. It works, but the problem is the that Application_AuthenticateRequest gets called for every single request, including javascript, css etc...
Moreover, it creates a redirect loop when I try to do Response.RedirectToRoute("Profile").
The only way I have found around this is to add the following to my IF statement before redirecting to the profile page:
!HttpContext.Current.User.HasProfile() && Request.Path != "/system/profile" && !Request.Path.Contains(".")
It checks if the current path is not the profile page (to prevent the redirect loop) and if there is a period in the URL (to allow javascript and css resources to continue to load). Is there a better way? How do you guys handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定这是否适用于每种情况,但我发现您可以询问当前上下文的 Handler 属性,并且对于静态资源它为 null。
I'm not sure if this will work for every single case, but I found that you can interrogate the Handler property of the current context, and it's null for static resources.