2012-09-27 166 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"); 
} 

我会复制这个,除非你有一个很好的理由不要。