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

4
我在控制器中有以下方法。
[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个回答

13
如果您正在将数据转换为字符串并使用contentType: 'application/json',那么请将令牌添加到ajax标头中,例如:
var headers = { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() };

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

然后您需要创建一个自定义的FilterAttribute来从Headers中读取值

[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,
    ....
});

将所有表单控件(包括令牌)序列化


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接