The required anti-forgery form field “__RequestVerificationToken” is not present Error in user Registration

后端 未结 19 1278
旧巷少年郎
旧巷少年郎 2020-11-29 22:12

I am using Membership.create user function, then the following error is occurring,

The required anti-forgery form field \"__RequestVerifi

19条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 22:27

    In my case I was getting this error while making an AJAX post, it turned out to be that the __RequestVerificationToken value wasn't being passed across in the call. I had to manually find the value of this field and set this as a property on the data object that's sent to the endpoint.

    i.e.

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

    Example

    HTML

      
    @Html.AntiForgeryToken()

    Javascript

    $(document).on('click', '#myForm .submitButton', function () {
      var myData = { ... };
      myData.__RequestVerificationToken = $('#myForm input[name="__RequestVerificationToken"]').val();
    
      $.ajax({
        type: 'POST',
        url: myUrl,
        data: myData,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        dataType: 'json',
        success: function (response) {
          alert('Form submitted');
        },
        error: function (e) {
          console.error('Error submitting form', e);
          alert('Error submitting form');
        },
      });
      return false; //prevent form reload
    });
    

    Controller

    [HttpPost]
    [Route("myUrl")]
    [ValidateAntiForgeryToken]
    public async Task MyUrlAsync(MyDto dto)
    {
        ...
    }
    

提交回复
热议问题