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

Mat*_*s F 2 asp.net-mvc forms-authentication

我有以下路线:

{语言}/{控制器} .mvc/{动作}/{ID}

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

HTTP://本地主机:4000 /德/ Account.mvc /注册

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

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

我怎样才能解决这个问题?

编辑

我使用了Darin的答案,但必须包含原始Authorize过滤器(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.
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

表单身份验证的问题是您不能拥有动态配置的登录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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)