2011-08-07 28 views
8

ReturnUrl有點醜。我想用redirect代替。如何與[Authorize]屬性一起指定應該用於表單身份驗證重定向URL的參數的名稱?或者我必須創建一個IAuthorizationFilter實現? :(如何更改ASP.NET MVC使用的「ReturnUrl」參數的名稱?

例子:

[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

對於/帳戶/登錄部分,我可以在Global.asax中修改我的路由並更改

<authentication mode="Forms"> 
    <forms loginUrl="~/account/logon" timeout="2880" /> 
</authentication> 

in web.config。但我不知道如何更改Ret urnUrl參數。

+0

我知道我對這個討論已經很晚了,但是我有同樣的問題,所以我發佈了一個針對Microsoft的增強請求。 http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3049874-make-returnurl-a-configurable-key-name-instead-o隨意爲它投票,評論它等。有了足夠的選票,它可能會引起他們的注意 –

回答

1

不在身邊最好的解決辦法,但它的工作原理...

<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> 
0

這裏的問題是重定向不是帖子。這是一個得到。在get上傳遞變量的唯一方法是使用某種類型的查詢字符串參數。你可以僞裝這個URL重寫,但它仍然是一個查詢參數,並通過URL傳遞。

也許你可以更清楚地知道你在找什麼?

+0

我不確定你是否理解我的問題......我添加了一個例子,希望這會使我要求的更清楚。 –

+0

是的,我明白你的意思了。這似乎發生在鏈條上。當401返回時,它被捕獲到鏈中併發出重定向。我正在研究它。 –

0

無法使用配置更改參數的名稱,因爲「ReturnUrl」參數名稱是在System.Web.Security.FormsAuthentication類中硬編碼的,該類是用於表單身份驗證的類,包括重定向。

實現所需結果的一種方法是擴展Authorize屬性,使其重定向到具有自定義參數名稱的登錄頁面。然後根據您使用的FormsAuthentication的其他方法,您也可以修改這些方法,特別是FormsAuthentication.RedirectFromLoginPage。

-1

參數名稱無法更改,這很煩人。我通過編寫自己的認證模塊解決了這個問題 - 你需要知道認證是如何工作的,但並不難 - 只要看看它是如何在反射器中完成的(也可以簡化它,我最終只使用來自FormsAuthentication的cookie加密/解密)。

+0

其實你可以改變,看http://msdn.microsoft.com/en-us/library/hh975440.aspx –

10

添加此鍵,你的web.config的appSettings部分

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

只需添加在你的web.config中appsettings部分下面的鍵值對:

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

這裏的問題和答案似乎與th舊形式認證的東西。在較新版本的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"的(可以是任何東西)。其餘的可能與您的項目不同。