表单身份验证重定向为Ajax提交

时间:2014-06-04 12:53:15

标签: jquery ajax model-view-controller

我正在研究MVC5 Web应用程序。有两种观点 -

  1. 主页
  2. 登录
  3. 当用户尝试访问主页视图时,他或她将被重定向到“登录”页面。因为相应的控制器使用授权属性进行修饰。

    Login视图的AjaxForm为 -

    @{
    var ajaxOptions = new AjaxOptions
                          {
                              HttpMethod = "POST",
                              InsertionMode = InsertionMode.Replace,                              
                              UpdateTargetId = "content",
                              LoadingElementId = "loader",
                              OnSuccess = "AjaxSuccess",
                              OnFailure = "AjaxError"
                          };
    }
    
    @using (Ajax.BeginForm("Authenticate", "Login", ajaxOptions, new { id = "LoginForm", @class = "login-form" }))
    {
        @Html.Raw(TempData["ErrorMessage"])
        ---Some code continues---
    

    现在用户填写他/她的凭据。该请求将转至验证以检查凭据。现在如果出现一些错误,我正在重新表现为 -

            [HttpPost]
            [AllowAnonymous]
            [ActionName("Authenticate")]
            public ActionResult Index(LoginModel model)
            {
                try
                {
                    // Some code for validation and redirecting by use of if
                    // But credentials not matched so show error    
                    TempData["ErrorMessage"] = string.Format(Login.ErrorDiv, "Incorrect username or password.");
                }
                catch (Exception exc)
                {
                    TempData["ErrorMessage"] = string.Format(Login.ErrorDiv, exc.Message);
                }
    
                // If we got this far, something failed, redisplay form
                return PartialView("_Login", model);
            }
    

    现在按照预期,登录表单即登录部分视图)应该重新显示错误。它没有发生。而是调用Get request for Login表单。整个表单(或整个视图)显示在 UpdateTargetId

    我从Fiddler检查了请求。请求进行身份验证。但随后表单被重定向回

    http://localhost/nsu/Login/Index?ReturnUrl=%2fnsu%2fLogin%2fAuthenticate
    

    我正在寻找帮助来解决这个奇怪的问题,继续使用AjaxForm进行登录。

1 个答案:

答案 0 :(得分:0)

此问题的答案是正确配置 web.config 中的表单身份验证设置。

将web.config配置为 -

    <authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>

其中loginUrl是Login视图的路径。操作名称为登录,控制器为 AccountController 。