2010-11-10 202 views
1

在經典的asp.net/mvc身份驗證示例中,LogOn操作獲取LogOnViewModel和returnUrl字符串以執行身份驗證並重定向到以前的Url。asp.net mvc身份驗證操作無法獲得returnUrl

[HttpPost] 
public ActionResult LogOn(LogOnViewModel model, string returnUrl) 
{ 
if (ModelState.IsValid) 
    if (!FormsAuthentication.Authenticate(model.UserName, model.Password))            
     ModelState.AddModelError("", "Incorrect user name or password."); 

    if (ModelState.IsValid) 
    { 
     FormsAuthentication.SetAuthCookie(model.UserName, false); 
     return Redirect(returnUrl ?? "Bookings"); 
    } 
    else 
     return View(); 
} 

但是,當通過操作處理請求時,returnUrl參數爲null,但是應該像作者說的那樣有一個值。有誰能解釋一下嗎?

形式從中我發送的請求是這樣的:查看/管理/ LogOn.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <div id="login"> 
    <% Html.EnableClientValidation(); %> 
    <% using (Html.BeginForm("LogOn", "Admin")) { %> 
     <%= Html.ValidationSummary(true) %> 
     <div><label>Username:</label><input name="userName" type="text" /></div> 
     <div><label>Password:</label><input name="password" type="password" /></div> 
     <div><input type="submit" value="Login" /></div> 
    <% } %> 
    </div> 
</asp:Content> 

有窗體上不產生隱藏字段。

認證:

<authentication mode="Forms"> 
    <forms loginUrl="~/Admin/LogOn" timeout="2880"> 
    <credentials passwordFormat="SHA1"> 
     <user name="admin" password="hashedPassword"/> 
    </credentials> 
    </forms> 
</authentication> 
+2

您的提交表單是什麼樣的?如果你用'POST'請求​​提交,你有''returnUrl'參數的隱藏元素嗎? – 2010-11-10 19:43:05

回答

5

當你去到沒有認證的頁面時,RETURNURL參數會自動添加到您的查詢字符串,當您通過MVC框架重定向到登錄頁面時。

您在視圖中的當前<form>標記沒有考慮到這一點。不管現有的任何QueryString值,它總是會採取相同的操作。

如果你使用:

<% using (Html.BeginForm()) { %> 
    // enter form html without the <form> tag 
<% } %> 

這將自動創建一個<form>標籤與考慮到已經在您的網頁上是否存在任何查詢字符串「行動」的價值。

+0

用戶想要調用的動作(www.mysite.com/Admin/Index)具有[授權]屬性,這就是他被重定向到登錄頁面的原因。登錄網址看起來像www.mysite.com/Admin/LogOn?ReturnUrl=%2fAdmin%2findex ///使用(Html.BeginForm())沒有解決問題,仍然爲空returnUrl – Maxim 2010-11-10 20:45:03

+0

hmm,檢查您的變量是適當的情況:ReturnUrl – Remus 2010-11-10 20:55:56

+1

試過了,沒有幫助。 Request.QueryString是空的。它聞起來很腥,它應該工作。這些請求路由的路由.MapRoute( 「AdminMainPage」, 「admin/{action}」, new {controller =「Admin」,action =「Index」} ); routes.MapRoute( 「AdminLogOn」, 「admin/logon /」, new {controller =「Admin」,action =「LogOn」} );無論如何,非常感謝 – Maxim 2010-11-10 21:06:30

1

也許嘗試包括你的形式隱藏輸入元素:

<%:Html.Hidden("returnUrl", yourUrlHere) %> 
+0

我不知道用戶從哪個頁面重定向到LogOn頁面。有什麼辦法可以知道嗎? – Maxim 2010-11-10 20:13:18

+1

查看Remus註釋,它會自動添加。不需要添加隱藏的輸入元素。 – jrob 2010-11-10 20:31:29