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

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
8 years ago
I am upgrading to 3.6 from 3.5.  I have a simple process, which displays Order notes via the Admin section. On 3.6 I am receiving the following error:

An exception of type 'System.Web.Mvc.HttpAntiForgeryException' occurred in System.Web.WebPages.dll but was not handled in user code

Additional information: The required anti-forgery form field "__RequestVerificationToken" is not present.

            var validator = new ValidateAntiForgeryTokenAttribute();
            validator.OnAuthorization(filterContext);

I have     @Html.AntiForgeryToken()  included in my view.  I've spent a number of days on this one.  I'm sure I'm missing something simple.  Please help!



Listed below is my code for Controller and View:

CONTROLLER

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Nop.Admin.Models.Orders;
using Nop.Core;
using Nop.Services.Helpers;
using Nop.Services.Orders;
using Nop.Services.Security;
using Nop.Services.Stores;
using Nop.Services.Vendors;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using Nop.Web.Framework.Mvc;



namespace Nop.Admin.Controllers
{
    public partial class TeapplixController : BaseAdminController
    {
        #region Fields

        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly IOrderProcessingService _orderProcessingService;
        private readonly IOrderService _orderService;
        private readonly IWorkContext _workContext;
        private readonly IPermissionService _permissionService;
        private readonly IStoreService _storeService;
        private readonly IVendorService _vendorService;

        #endregion

        #region Constructors

        public TeapplixController(IDateTimeHelper dateTimeHelper,
                                    IOrderProcessingService orderProcessingService,
                                    IOrderService orderService,
                                    IWorkContext workContext,
                                    IPermissionService permissionService,
                                    IStoreService storeService,
                                    IVendorService vendorService)
        {
            this._dateTimeHelper = dateTimeHelper;
            this._orderProcessingService = orderProcessingService;
            this._orderService = orderService;
            this._workContext = workContext;
            this._permissionService = permissionService;
            this._storeService = storeService;
            this._vendorService = vendorService;
        }

        #endregion

        #region Methods

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }


        public ActionResult List()
        {
            return View();
        }
        [HttpPost]
        public ActionResult OrderList(DataSourceRequest command, List<OrderModel.OrderNote> model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTeapplix))
                return AccessDeniedView();

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null)
            {
                //model.VendorId = _workContext.CurrentVendor.Id;
            }

            //load orders
            var notes = _orderService.GetAllOrderNotes(command.Page - 1, command.PageSize);
            var gridModel = new DataSourceResult
            {
                Data = notes.Select(x => new OrderModel.OrderNote()
                {
                    Id = x.Id,
                    OrderId = x.OrderId,
                    CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc),
                    Note = x.Note
                }),
                Total = notes.TotalCount
            };

            return new JsonResult
            {
                Data = gridModel
            };
        }




        public ActionResult SendToTeapplix(int id)
        {
            _orderProcessingService.SendOrderToTeapplixFromAdminPanel(id, false);
            return RedirectToAction("List");
        }

        #endregion
    }
}


VIEW is as follows:

@model OrderListModel
@{
    var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    //page title
    ViewBag.Title = T("Admin.System.Teapplix").Text;
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.System.Teapplix")
        </div>
    </div>

    <table class="adminContent">
        <tr>
            <td>
                <div id="orders-grid"></div>
                <script id=" ">
                    $(document).ready(function () {
                        $("#orders-grid").kendoGrid({
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("OrderList", "Teapplix"))",
                                        type: "POST",
                                        dataType: "json"

                                    }
                                },
                                schema: {
                                    data: "Data",
                                    total: "Total",
                                    errors: "Errors"
                                },
                                error: function(e) {
                                    display_kendoui_grid_error(e);
                                    // Cancel the changes
                                    this.cancelChanges();
                                },
                                pageSize: @(defaultGridPageSize),
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true
                            },
                            pageable: {
                                refresh: true
                            },
                            editable: {
                                confirmation: false,
                                mode: "inline"
                            },
                            scrollable: false,
                            columns: [{
                                field: "OrderId",
                            }, {
                                field: "CreatedOn",
                                template: "#= kendo.toString(kendo.parseDate(CreatedOn, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
                            },

                            {
                                field: "Note",
                            }, {
                                field: "OrderId",
                                title: "@T("Teapplix.Send")",
                                width: 200,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '<a href="SendToTeapplix/#=OrderId#">@T("Teapplix.Send")</a>'
                            }]
                        });
                    });
                </script>
            </td>
        </tr>
    </table>
}
8 years ago
Are you cleaning your solution and recompiling? If you don't the older version  of your view will be used.

Hope this helps.

Kevin
8 years ago
You don't need the antiforgery code on KendoUI pages. or at least I didn't have to implement it there.
8 years ago
Thanks for your reply.  Yes, I have cleaned and recompiled.  May be irrelevant, this is custom code I added to Nop.Admin.  It isn't a Plug-in.
8 years ago
Initially I did not have the Antiforgery code installed, yet received the error.  Thus, I added it.  I still receive the same error.  Any other suggestions, even as unreasonable as they seem?
8 years ago
Is the view using this UI element something you've created or is it being used by an internal NOP view? Perhaps you need to add the token to the parent page?

Just a guess??

Kevin
8 years ago
Kevin - This is a UI I created.  I added it to the System dropdown in Admin.
8 years ago
Hello,

M getting this error too, but  for a change I am trying to submit the form using ajax. at that time it goes to error function and getting response as
" The required anti-forgery form field "__RequestVerificationToken" is not present."

I have tried different solutions to add this token value in ajax headers, along with the formdata to post. But none of them worked.

Kindly find the below code, which gets executed when click on New Account in register module.

var form = $('#registerForm');
                var dataObject = $('#registerForm').serializeObject();
                var token = form.find('[name=__RequestVerificationToken]').val();
                dataObject["__RequestVerificationToken"] = token;
                var formData = JSON.stringify(dataObject);// store json string
                var headers = {};
                headers['__RequestVerificationToken'] = token
                $.ajax({
                    type: 'POST',
                    url: 'Customer/Register',
                    headers: headers,
                    data:  formData,
                    contentType: 'application/json',
                    dataType: "json",
                    success: function (data) {
                        alert("success=" + data);
                    },
                    error: function (data) {
                        alert("error=" + data);
                    }
                });

Have tried all permutation that i found in stackoverflow or from any nopcommerce blog but didn't get success. Please anyone if you have the solution to post the model along with this security token, do reply at the earliest.

Regards
7 years ago
After upgrade one of my plugin from 3.4 to 3.7 I have also face this error. Can anybody solve this issue? If so please share.
7 years ago
sina.islam wrote:
After upgrade one of my plugin from 3.4 to 3.7 I have also face this error. Can anybody solve this issue? If so please share.


Add anti-forgery token with your post data

or try with like bellow


[HttpPost]
        [AdminAntiForgery(true)]
        public ActionResult ActionName(FormCollection form)
{
//
}
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.