如何获取jQuery Ajax调用以张贴到以ValidateAntiForgeryToken装饰的Action

时间:2018-07-03 10:16:40

标签: jquery ajax asp.net-mvc action

在我的一个控制器中,如果我用[ValidateAntiForgeryToken]属性修饰了该动作方法,则该动作方法将不会执行。

更多信息:我有剃刀代码来生成从隐藏字段中检索到的令牌。我已将其合并到我的jQuery Ajax调用中(该调用将模型和另一个值传递给控制器​​操作(AccountController.Login)。它从不执行该操作。我在这里缺少什么?

控制器:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
     ...std MVC Identity Login code..
}

“登录”视图中的标记(即没有标签)(在JQuery模式中)

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
    {
        @Html.AntiForgeryToken()
    }
    <div>...login markup</div>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#btnSubmit").on("click", function ()
            {
                var modeldata = { Email: $('#txtUserEmail').val(), Password: $('#txtPwd').val() };
                var returnUrl = null;

                var form = $('#__AjaxAntiForgeryForm');
                var token = $('input[name="__RequestVerificationToken"]').val();

                alert(token);
                $.ajax({
                    url: "/Account/Login",
                    type: "POST",
                    data: { __RequestVerificationToken: token, model: modeldata, returnUrl: returnUrl },
                    async: false,
                    dataType: 'JSON', //do not use JSON , because the server is expecting the __RequestVerificationToken parameter to be part of the POST request payload
                    contentType: 'application/x-www-form-urlencoded; charset=utf-8',

                    success: function (ViewResult)
                    {
                        if (ViewResult === "0")
                        {
                            window.location.href='@Url.Action("Index","Home")'
                        }
                        else
                        {
                            $('#dialogL').replaceWith(ViewResult);
                        }
                    }
                });
            });
        });
    </script>

0 个答案:

没有答案