How to include the @Html.AntiForgeryToken() when deleting an object using a Delete link

后端 未结 2 1089
轮回少年
轮回少年 2020-12-29 10:00

i have the following ajax.actionlink which calls a Delete action method for deleting an object:-

 @if (!item.IsAlreadyAssigned(item         


        
2条回答
  •  执笔经年
    2020-12-29 10:28

    Modifying the answer by Bronx:

    $.ajaxPrefilter(function (options, localOptions, jqXHR) {
        var token, tokenQuery;
        if (options.type.toLowerCase() !== 'get') {
            token = GetAntiForgeryToken();
            if (options.data.indexOf(token.name)===-1) {
                tokenQuery = token.name + '=' + token.value;
                options.data = options.data ? (options.data + '&' + tokenQuery) 
                    : tokenQuery;
            }
        }
    });
    

    combined with this answer by Jon White

    function GetAntiForgeryToken() {
      var tokenField = $("input[type='hidden'][name$='RequestVerificationToken']");
      if (tokenField.length == 0) { return null; 
      } else {
      return {
         name: tokenField[0].name,
         value: tokenField[0].value
      };
    }
    

    Edit sorry - realised I am re-inventing the wheel here SO asp-net-mvc-antiforgerytoken-over-ajax/16495855#16495855

提交回复
热议问题