2012-05-22 47 views
0

我正在將我的項目從asp.net web表單升級到MVC4,一步一步。在第一步中,我更改了登錄頁面和其他幾個頁面。我使用表單身份驗證,用我自己的邏輯(沒有成員資格) - 我檢查數據庫表的用戶名/密碼。如果確定,用戶將被重定向到目的地。 我登錄的代碼是:從asp.net WebForms遷移到MVC時的表單身份驗證問題

Web.config文件:

<authentication mode="Forms"> 
    <forms loginUrl="~/LogIn" name=".ASPXFORMSAUTH" timeout="150" /> 
</authentication> 
<authorization> 
    <deny users="?" /> 
</authorization> 

登錄控制器:

[AllowAnonymous] 
[HttpPost] 
public ActionResult AjaxLogin(FormCollection postedFormData) 
{ 
    try 
    { 
     string userName = postedFormData["Login_UserName"]; 
     string password = postedFormData["Login_Password"]; 
     UserEntity userEntity = new UserEntity(Utilities.AuthenticateUser(userName, password, 1)); 

     Session["UserEntity"] = userEntity; 

     FormsAuthentication.SetAuthCookie(userEntity.Key.Id.ToString(), false); 

     return Json(new { redirectToUrl = "./AccountSelection", error = "false", lan = Thread.CurrentThread.CurrentUICulture.ToString() }); 
    } 
    catch (Exception ex) 
    { 
     return Json(new { redirectToUrl = "", error = ExceptionHandler.HandleException(ex), lan = Thread.CurrentThread.CurrentUICulture.ToString() }); 
    } 
} 

當我嘗試登錄我得到HTTP 302重定向回登錄。 如果我刪除的web.config中的「授權」部分它會正常工作,但現在我有兩個問題:

  1. 我已經把每個控制器
  2. 我的web表單不會對[授權]屬性內部表單認證(可以直接訪問,無需登錄!!)

我在做什麼錯?

回答

2

如果您在web.config中定義授權,則不需要AllowAnonymousAttribute。

話雖如此,您似乎沒有將AjaxLogin添加到您的授權列表。這是必要的,因爲否則Ajax請求將被阻止。您需要〜/ Login和〜/ Account/AjaxLogin路徑。您可能還需要〜/帳戶/登錄路徑,但我不確定。

+0

感謝您的幫助。我嘗試在web.config中添加「〜/ Secure/AjaxLogin」,但它沒有幫助。 (我給擊潰路徑,向控制器):'<位置路徑= 「〜/登錄」> <授權> <允許用戶= 「*」/> <位置路徑= 「〜/安全/ AjaxLogin」> <授權> <允許用戶= 「*」/> ' –

+0

@Yaniv - 您是否更改控制器名SecureController? –

+0

是的,我做了 - 控制器被命名爲 - 「SecureController」。這是問題嗎? –