如何更改ASP.NET MVC使用的“ReturnUrl”参数的名称?

ReturnUrl有点难看。 我想改用直接redirect 。 如何指定应与表单身份validation重定向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中修改我的路由并进行更改

    

在web.config中。 但我不知道如何更改ReturnUrl参数。

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

  

这里的问题和答案似乎与旧表格认证的东西有关。 在较新版本的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( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) }, ReturnUrlParameter = "redirect" }); 

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

不是最好的解决方案,但它的工作原理……

        

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

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

无法使用配置更改参数的名称,因为“ReturnUrl”参数名称在System.Web.Security.FormsAuthentication类中进行了硬编码,该类是用于表单身份validation的类,包括重定向。

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

参数名称无法更改,这很烦人。 我通过编写自己的身份validation模块解决了这个问题 – 您需要知道身份validation的工作原理,但这并不难 – 只要看看它是如何在reflection器中完成的(并且可能简化它,我最终只使用了FormsAuthentication中的cookie加密/解密)。

只需在键值对后面的appSettings部分添加web.config: