How To Add AntiForgery Token To Syncfusion Grid Request For Data

Viewed 35

Scenario

I'm using Syncfusion UI controls in a Razor Pages Net6 application, but I'm having issues with antiforgery validation when requesting data for the grid...

Example:

// ------------- Books.cshtml

    @page
    @model Site.Pages.BooksModel
    @using Syncfusion.EJ2
    @{
    }
    @Html.EJS().Grid("BooksIndexGrid").DataSource(dataManager => { 
        dataManager.Url("/books?handler=GetGridData");
        dataManager.Adaptor("UrlAdaptor");
    }).Columns(col =>
    {
                col.Field("title").Add();
    }).AllowPaging().AllowSorting().Render()

//-------------  Books.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Site.Pages
{
    public class BooksModel : PageModel
    {
        private readonly IMediator _mediator;

        public BooksModel(IMediator mediator)
        {
            _mediator = mediator;
        }

        public void OnGet()
        {
        }

        public async Task<JsonResult> OnPostGetGridDataAsync(DataManagerRequest dm)
        {
            //Filtering logic removed for brevity

            var data = await _mediator.Send(new GetListOfBooksRequest());

            return new JsonResult(new { result = data, count = data.Count() });
        }
    }
}

Issue

The example above returns a 400 error code because it requests the data using a POST method and the Antiforgery token is not present in the request. So the question is...

How do I add the required Antiforgery token to the request to read the data?

Ive found this article on creating a custom Adapter, but it only seems to cover CUD and not CRUD:

https://ej2.syncfusion.com/aspnetcore/documentation/grid/how-to/perform-crud-operation-using-anti-forgery-token

I know I can disable the check for the antiforgery token, but do not wish to do that.

1 Answers

You can use the same approach used in this forum and implement custom adaptor from where you can send the anti-forgery token on performing CRUD actions.

This is demonstrated in the below code snippet,

window.customAdaptor = new ej.data.UrlAdaptor();

customAdaptor = ej.base.extend(customAdaptor, {

processResponse: function (data, ds, query, xhr, request, changes) {
    request.data = JSON.stringify(data);
    return ej.data.UrlAdaptor.prototype.processResponse.call(this, data, ds, query, xhr, request, changes)
},
insert: function (dm, data, tableName) {
    return {
        url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url,
        data: jQuery.param({
            __RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
            value: data,
            table: tableName,
            action: 'insert'
        }),
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
   }
},
remove: function(dm, keyField, value, tableName, query) {
    return {
        url: dm.dataSource.removeUrl || dm.dataSource.crudUrl || dm.dataSource.url,
        data: jQuery.param({
            __RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
            key: value,
            keyColumn: keyField,
            table: tableName,
            action: 'remove'
        }),
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
    };
},
update: function (dm, keyField, value, tableName) {
    return {
        url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url,
        data: jQuery.param({
            __RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
            value: value,
            table: tableName,
            action: 'insert'
        }),
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
    };
},

});

var dataManger3 = new ej.data.DataManager({ url: "Home/GetHierachyGridData", crudUrl: "Home/CrudUpdate", adaptor: customAdaptor, crossDomain: true });

We have modified the shared sample based on this for your reference. You can find it below,

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/Sample1Updated-486561763

More details on the custom adaptor can be checked in the below documentation link,

Documentation: https://ej2.syncfusion.com/javascript/documentation/grid/data-binding/#custom-adaptor

Let us know if you have any concerns.

Related