2012-09-27 218 views
2

我想向mvc網站添加窗體身份驗證,當我運行應用程序時,我被重定向到登錄頁面(這是正確的)。但是,每次嘗試登錄時,頁面都會刷新,而控制器永遠不會收到請求。我認爲我的表單身份驗證的某些內容已關閉,並將所有請求重定向回登錄頁面?任何幫助將不勝感激!下面mvc窗體身份驗證重定向

是我的web配置信息:

<authentication mode="Forms"> 
     <forms loginUrl="~/Account" timeout="30" slidingExpiration="false" requireSSL="false" />  
    </authentication> 
<authorization> 
     <deny users ="?" /> 
     <allow users = "*" /> 
    </authorization> 

下面是我的登錄頁面:

@using (Html.BeginForm("Login", "Account", FormMethod.Post)) 
{ 
    @Html.LabelFor(x => x.Username)<br /> 
    @Html.TextBoxFor(x => x.Username) 

    <br /> 
    <br /> 

    @Html.LabelFor(x => x.Password)<br /> 
    @Html.TextBoxFor(x => x.Password) 


    <br /> 
    <br /> 
    <br /> 

    <input type="submit" value="Login" /> 
} 

下面是我的控制器:

[HttpGet] 
     public ActionResult Index() 
     { 
      return View("~/Views/Account/Login.cshtml", new LoginViewModel()); 
     } 

     [HttpPost] 
     public ActionResult Login(LoginViewModel viewModel) 
     { 
      Membership.ValidateUser(viewModel.Username, viewModel.Password); 
      FormsAuthentication.SetAuthCookie(viewModel.Username, viewModel.RememberMe); 

      return View("~/Views/Account/Login.cshtml", viewModel); 
     } 

回答

2

我認爲POST發生了,但是你有我的朋友的問題是你重定向到POST末尾的登錄頁面。

return View("~/Views/Account/Login.cshtml", viewModel); 

將用戶引導至主頁。

+0

謝謝,這工作! – spyter

+1

@ user587950,很高興我可以提供幫助,請將其標記爲我自己和社區的答案! –

1

這是正確的。 因爲該代碼的:

public ActionResult Index() 
{ 
    return View("~/Views/Account/Login.cshtml", new LoginViewModel()); 
} 

將其更改爲return View(); 和CREATE VIEW命名指數在相應的文件夾。

2

其他人建議從您的Login HttpPost操作重定向到主頁,但由Visual Studio創建的標準MVC「Intranet Application」模板嘗試重定向到作爲查詢字符串傳遞給Login操作的returnUrl, FormsAuthentication架構:

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
{ 
    return Redirect(returnUrl); 
} 
else 
{ 
    return RedirectToAction("Index", "Home"); 
} 

我會複製這個,除非你有一個很好的理由不要。