asp.net-mvc - 如何在重定向到login.aspx后保留url中的参数

标签 asp.net-mvc forms-authentication

我有以下路线:

{语言}/{ Controller }.mvc/{ Action }/{id}

一旦用户选择了语言,就会以路由值语言进行维护。

http://localhost:4000/de/Account.mvc/Register

如果用户点击需要授权的页面,我就会遇到问题。然后他被重定向到http://localhost:4000/Account.mvc/Login?ReturnUrl=%2fde%2fAccount.mvc%2fProfileData

登录页面在 web.config 中配置,不允许使用来自路由的参数。登录后的页面正常( http://localhost:4000/de/Account.mvc/ProfileData ),但登录页面本身没有路由值语言。

我该如何解决这个问题?

编辑

我使用了 Darin 的答案,但必须包含原始授权过滤器 (AuthorizeAttribute.cs) 中的所有代码。原因记录在该文件中。它处理未经授权的用户可能从缓存获取安全页面的情况。

这是代码中的注释:

            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.

最佳答案

表单例份验证的问题是您无法动态配置登录 URL。这正是 ASP.NET 团队设计框架的方式。有时会调用 FormsAuthentication.RedirectToLoginPage 方法,该方法将重定向到 web.config 中的硬编码 url。

我可以看到两种可能的解决方法:

  1. 不要将语言存储在 URL 中,而是存储在 Cookie 中
  2. 编写一个自定义 ActionFilter,如果用户未通过身份验证,该过滤器会重定向到动态构建的登录页面

以下是使用自定义属性的示例:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class RequiresAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectResult("CALCULATE YOUR LOGIN URL HERE FROM ROUTES");
        }
    }
}

关于asp.net-mvc - 如何在重定向到login.aspx后保留url中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886862/

相关文章:

javascript - Expressjs 如何在用户登录时显示/隐藏 div

c# - MVC : Submitting a view to itself - avoid model property values in return URL

asp.net-mvc - ModelClientValidationRule 类用法

c# - 如何通过 SignalR 实现 'Who is typing' 功能?

asp.net - 我的带有表单例份验证的 ASP.NET MVC2 应用程序甚至阻止对图像、样式和脚本的访问

c# - ASP.NET MVC中如何实现基于Session数据的授权检查?

ASP.NET Forms 身份验证需要启用匿名

c# - 有条件地将 htmlAttributes 添加到 ASP.NET MVC Html.ActionLink

c# - OWIN 能否替代 ASP.NET MVC 应用程序中的 DI?

asp.net - 我应该如何/应该保留 ClaimsPrincipal?