如何更改&;returnurl &;参数.净MVC

本文关键字:MVC 参数 returnurl 何更改 | 更新日期: 2023-09-27 18:04:56

ReturnUrl有点丑。我想用redirect代替。我如何指定应该用于表单认证重定向url与[Authorize]属性结合的参数名称?还是我必须创建一个IAuthorizationFilter实现?(

的例子:

[Authorize]
public class Tools : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

当一个没有登录的用户访问http://example.com/tools时,我希望他们被重定向到http://example.com/account/logon?redirect=%2ftools,而不是默认的http://example.com/Account/LogOn?ReturnUrl=%2ftools

对于/account/logon部分,我可以在Global中修改路由。Asax和change

<authentication mode="Forms">
  <forms loginUrl="~/account/logon" timeout="2880" />
</authentication>
在web . config中

。但是我不知道如何改变ReturnUrl参数

如何更改&;returnurl &;参数.净MVC

将此键添加到web.config的appSettings部分

<add key="aspnet:FormsAuthReturnUrlVar" value="redirect" />

这里的问题和答案似乎与旧的表单身份验证有关。在较新的MVC版本上,例如MVC 5(带有Identity 2.0),您可以在Startup.Auth.cs中做这样的事情:

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/account/login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            ReturnUrlParameter = "redirect"
        });

重要的部分当然是ReturnUrlParameter = "redirect"(可以是任何东西)。其余部分可能与您的项目不同。

不是最好的解决方案,但它有效…

<rule name="FormsAuthentication" stopProcessing="true">
  <match url="^account/log(i|o)n$" />
  <conditions>
    <add input="{QUERY_STRING}" pattern="^ReturnUrl=([^=&amp;]+)$" />
  </conditions>
  <action type="Redirect" url="account/logon?redirect={C:1}" appendQueryString="false" />
</rule>

这里的问题是,重定向不是一个帖子。这是一个get。在get上传递变量的唯一方法是使用某种类型的查询字符串参数。你可以掩饰这个url重写,但它仍然是一个查询参数,并传递url。

也许你可以更清楚一点你在找什么?

只需添加您的web。在键值对后面的appSettings部分配置:

<add key="aspnet:FormsAuthReturnUrlVar" value="your-custom-parameter-name"/>

无法使用configuration更改参数名,因为"ReturnUrl"参数名在System.Web.Security.FormsAuthentication类中是硬编码的,该类用于表单身份验证,包括重定向。

实现预期结果的一种方法是扩展Authorize属性,使其重定向到使用自定义参数名称的登录页面。然后,根据您使用的FormsAuthentication的其他方法,您也可以修改这些方法,特别是FormsAuthentication. redirectfromloginpage。

参数名不能更改,这很烦人。我通过编写自己的身份验证模块来解决这个问题-您需要知道身份验证是如何在内部工作的,但这并不难-只需看看它是如何在反射器中完成的(并可能简化它,我最终只使用FormsAuthentication的cookie加密/解密)。