在ajax调用中不存在所需的防伪表单字段“__RequestVerificationToken”

时间:2017-08-19 16:06:30

标签: javascript jquery asp.net-mvc asp.net-ajax

我在控制器中有以下方法

[HttpPost]
    [Authorize(Roles ="Klient")]
    [ValidateAntiForgeryToken]
    public ActionResult GetAvaiableHouses(DateTime startDate, DateTime endDate)
    {
        Session.Remove("Reservation");
        IEnumerable <SelectListItem> avaiableHouses = repository.GetAllNamesAvaiableHouses(repository.GetAvaiableHousesInTerm(startDate, endDate));

        List<string> houses = new List<string>();
        avaiableHouses.ToList().ForEach(item => houses.Add(item.Value));

        if(avaiableHouses.ToList().Count == 0)
        {
            return new EmptyResult();
        }

        Session["Reservation"] = new NewReservation()
        {
            StartDate = startDate,
            EndDate = endDate,
            AvaiableHouses = avaiableHouses
        };

        return PartialView("~/Views/Shared/_AvaiableHousesPartial.cshtml", houses);
        }

使用View.cshtml中的ajax脚本调用此方法

$(function () {
    $("#btnCheckAvaiableHouses").click(function () {

        $.ajax({
            type: "POST",
            url: "/ClientReservations/GetAvaiableHouses",
            data: '{startDate: "' + $("#startdate").val() + '",endDate:"' + $("#enddate").val() + '",__RequestVerificationToken:"' + $('input[name=__RequestVerificationToken]').val() +'"  }',
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            success: function (response) {
                $('#avaiableHouses').html(response)
                if (!$('#avaiableHouses').is(':empty')) {
                    document.getElementById("btnConfirmTerm").style.visibility = 'visible';
                }
                else {
                    $('#avaiableHouses').html('Brak dostępnych domków w podanym terminie')
                }

            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    });
});

这是按钮的一部分,用于调用此脚本

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" id="btnCheckAvaiableHouses" value="Sprawdź dostępność domków" class="btn btn-default" /> 
                <input type="button" id="btnConfirmTerm" value="Potwierdź termin" onclick="location.href='@Url.Action("Create", "ClientReservations")'"  class="btn btn-default" style="visibility:hidden" />
            </div>
        </div>

我添加了附加参数

'",__RequestVerificationToken:"' + $('input[name=__RequestVerificationToken]').val() 

进入ajax脚本但在执行期间我仍然收到错误

  

,__ RequestVerificationToken不存在。

可能是什么原因?

1 个答案:

答案 0 :(得分:0)

如果您使用contentType: 'application/json对数据进行字符串化,则将令牌添加到ajax标头中,例如

var headers = { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() };

$.ajax({
    headers: headers,
    data: ... // remove the token from your existing implementation
    ....
});

然后你需要创建一个自定义FilterAttribute来读取标题中的值

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        var httpContext = filterContext.HttpContext;
        var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
        AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
    }
}

并在您的控制器方法中,将[ValidateAntiForgeryToken]替换为[ValidateHeaderAntiForgeryToken]

但是,没有必要对数据进行字符串化,您可以使用

var data = {
    startDate: $("#startdate").val(),
    endDate: $("#enddate").val(),
    __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};

$.ajax({
    data: data,
    ....
});

并删除contentType选项,使其使用默认的'application/x-www-form-urlencoded; charset=UTF-8'

您尚未展示自己的表单,假设其中包含@Html.AntiForgeryToken()@Html.TextBoxFor(m => m.startDate)以及@Html.TextBoxFor(m => m.endDate),您可以使用name="startDate"name="endDate"生成表单控件,然后你可以简单地使用

var data = $('form').serialize();

$.ajax({
    data: data,
    ....
});

序列化所有表单控件,包括令牌