jquery – 如何在mvc中使用防伪令牌进行ajax请求

前端之家收集整理的这篇文章主要介绍了jquery – 如何在mvc中使用防伪令牌进行ajax请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下问题,下面的MVC项目的细节。

当我试图使用jquery ajax请求与加载面板,如旋转gif(甚至文本),我得到错误,从提琴家观察到

The required anti-forgery form field “__RequestVerificationToken” is not present.

如果我发表评论
[ValidateAntiForgeryToken]属性在POST操作方法和使用加载面板它是正常工作。我想知道为什么我得到这个错误

我甚至使用序列化的查询字符串

__RequestVerificationToken= $('input[name="__RequestVerificationToken"').val()

仍然我得到错误

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster,ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys.

AutoGenerate不能在群集中使用

我应该使用什么?

这里更新了问题码

var token = $('input[name="__RequestVerificationToken"]').val();
$('#submitaddress').click(function subaddr(event) {
    event.preventDefault();
    event.stopPropagation();
  //$('#addAddress').html('<img src="/img/animated-overlay.gif"> Sending...');
   // $('#addAddress').blur();
    //  $(this).bl
    if ($('#Jobid').val()!="") {
        $('#TransportJobId').val(parseInt($('#Jobid').val()));
        $.ajax(
              {
                  url: '/TransportJobAddress/create',type: 'POST',data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJobAddress/Create"]').serialize(),success: function poste(data,textStatus,jqXHR) { $('#addAddress').html(data); return false; },error: function err(jqXHR,errorThrown) { alert('error at address :' + errorThrown); }
              });
    }
    else {
        var transportid = 2;
        $.ajax({
            url: '/TransportJob/create',data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJob/Create"]').serialize(),success: function sfn(data,jqXHR) {
                transportid = parseInt(data);
                $('#Jobid').val(data);
               // alert('inserted id :' + data);
                $('#TransportJobId').val((transportid));
                $.ajax(
         {

             url: '/TransportJobAddress/create',//beforeSend: function myintserver(xhr){  
             //        $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');
             //},jqXHR) {
                 $('#addAddress').html(data);

             },errorThrown) {
                 alert('error at address :' + errorThrown);
             }

         });
            },error: function myfunction(jqXHR,errorThrown) {
                alert("error at transport :" + jqXHR.textStatus);
            },complete: function completefunc() {
              //  alert('ajax completed all requests');
                return false;
            }

        });
    }
});

表单标签

<form action="/TransportJob/Create" method="post"><input     name="__RequestVerificationToken" type="hidden"   value="ydYSei0_RfyBf619dQrhDwwoCM7OwWkJQQEMNvNdAkefiFfYvRQ0MJYYu0zkktNxlJk_y1ZJO9-yb-  COap8mqd0cvh8cDYYik4HJ0pZXTgE1" />

运输工具
表单标签2在同一页面

<form action="/TransportJobAddress/Create" method="post" novalidate="novalidate"><input name="__RequestVerificationToken" type="hidden"    value="Np2vUZJPk1TJlv846oPSU6hg4SjMHRcCk1CacaqZbpHOg8WbV4GZv06noRDl7F_iT9qQf3BIXo3n9wGW68sU mki7g3-ku_BSHBDN-g2aaKc1">

解决方法

你将你的令牌添加到ajax调用的头吗?

您需要在ajax调用中的消息头中添加AntiForgeryToken:

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

var headers = {};

headers['__RequestVerificationToken'] = token;

$.ajax({
        url: ... some url,headers: headers,....
});

在你的代码中尝试这样

var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr = $('form[action="/TransportJobAddress/Create"] input[name="__RequestVerificationToken"]').val(); 

var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;

$('#submitaddress').click(function subaddr(event) {
    event.preventDefault();
    event.stopPropagation();
  //$('#addAddress').html('<img src="/img/animated-overlay.gif"> Sending...');
   // $('#addAddress').blur();
    //  $(this).bl
    if ($('#Jobid').val()!="") {
        $('#TransportJobId').val(parseInt($('#Jobid').val()));
        $.ajax(
              {
                  url: '/TransportJobAddress/create',headers:headersadr,headers:headers,data: $('form[action="/TransportJob/Create"]').serialize(),data: $('form[action="/TransportJobAddress/Create"]').serialize(),complete: function completefunc() {
              //  alert('ajax completed all requests');
                return false;
            }

        });
    }
});

在您的ajax调用添加标题行。

原文链接:https://www.f2er.com/jquery/183575.html

猜你在找的jQuery相关文章