- Home
- Forum
- ASP.NET MVC - EJ 2
- Anti-forgery token return error
Anti-forgery token return error
Please get back to us if you need further assistance.
Regards
Praveenkumar G
Hi Praveenkumar,
thank you for your support.
In the documentation you have indicated to me, "UrlAdaptor" is used, instead I need to use the "RemoteSaveAdaptor".
The example, with RemoteSaveAdaptor, given at this link:https://ej2.syncfusion.com/aspnetmvc/documentation/grid/how-to/#perform-crud-operation-using-anti-forgery-token is not working because it returns to me the error I indicated in the thread open message.
|
[index.cshtml]
@Html.AntiForgeryToken()
<div>
<div>
@Html.EJS().Grid("GridSocios").DataSource(dataManager => { dataManager.Json(ViewBag.datasource.ToArray()).InsertUrl("/Home/InsertR").RemoveUrl("/Home/RemoveR").UpdateUrl("/Home/UpdateR").Adaptor("RemoteSaveAdaptor"); }).Load("loadSoc").AllowSelection().Height("300").Columns(col =>
{
col.Field("OrderID").HeaderText("OrderID").IsPrimaryKey(true).Add();
col.Field("OrderDate").HeaderText("OrderDate").EditType("datepickeredit").Add();
col.Field("CustomerID").HeaderText("FirstName").Add();
col.Field("ShipCountry").HeaderText("ShipCountry").Add();
}).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).ShowDeleteConfirmDialog(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).SelectionSettings(select => select.Type(Syncfusion.EJ2.Grids.SelectionType.Single)).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
</div>
</div>
<script>
window.socAdaptor = new ej.data.RemoteSaveAdaptor();
socAdaptor = ej.base.extend(socAdaptor, {
insert: function (dm, data, tableName) {
return {
url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url,
data: JSON.stringify({
__RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
value: data,
table: tableName,
action: 'insert'
}),
contentType: 'application/json; charset=utf-8',
}
},
update: function (dm, keyField, value, tableName) {
return {
type: 'POST',
url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url,
data: JSON.stringify({
__RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
value: value,
table: tableName,
keyColumn: keyField,
key: value[keyField],
action: 'update'
}),
contentType: 'application/json; charset=utf-8',
};
},
remove: function (dm, keyField, value, tableName) {
return {
url: dm.dataSource.removeUrl || dm.dataSource.crudUrl || dm.dataSource.url,
data: JSON.stringify({
__RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
key: value,
keyColumn: keyField,
table: tableName,
action: 'remove'
}),
contentType: 'application/json; charset=utf-8',
};
},
});
function loadSoc(args) {
this.dataSource.adaptor = socAdaptor;
this.dataSource.dataSource.headers = [{ 'XSRF-TOKEN': $("input:hidden[name='__RequestVerificationToken']").val() }];
}
</script>
|
|
[HomeControllers.cs]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateR([FromBody]CRUDModel<OrdersDetails> myObject)
{
var ord = myObject;
OrdersDetails val = OrdersDetails.GetAllRecords().Where(or => or.GetType().GetProperty(myObject.KeyColumn).GetValue(or).ToString() == myObject.Key.ToString()).FirstOrDefault();
if (val != null)
{
val.OrderID = ord.Value.OrderID;
val.EmployeeID = ord.Value.EmployeeID;
val.CustomerID = ord.Value.CustomerID;
val.Freight = ord.Value.Freight;
val.OrderDate = ord.Value.OrderDate;
val.ShipCity = ord.Value.ShipCity;
val.ShipAddress = ord.Value.ShipAddress;
val.ShippedDate = ord.Value.ShippedDate;
val.ShipCountry = ord.Value.ShipCountry;
}
return Json(ord.Value);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult InsertR(OrdersDetails value)
{
var ord = value;
OrdersDetails.GetAllRecords().Insert(0, ord);
return Json(value);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RemoveR([FromBody]CRUDModel<OrdersDetails> value)
{
OrdersDetails.GetAllRecords().Remove(OrdersDetails.GetAllRecords().Where(or => or.OrderID == int.Parse(value.Key.ToString())).FirstOrDefault());
return Json(value);
} |
|
[startup.cs]
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
|
Hi Rajapandiyan
even the code you suggested to me gives me the same error as you can see from the image.
However, it is a project ASP.NET MVC and not Core
- Share the full code you have used.
- Share the response details in Network Tab.
- Please ensure whether you extend RemoteSaveAdaptor or something else?
- If possible share a simple issue reproducible sample which will be very helpful to resolve this.
Hi Rajapandiyan,
This is View:
<div class="card shadow mb-4">
<div class="card-body">
@Html.AntiForgeryToken()
@(Html.EJS().Grid<ImpostazioniVM>("GridImpostazioni").DataSource(dataManager => { dataManager.Json(((IEnumerable<ImpostazioniVM>)Model).ToArray()).UpdateUrl("UpdImpostazioni").Adaptor("RemoteSaveAdaptor"); }).Load("load").Columns(col =>
{
col.Field("IdImpostazione").IsPrimaryKey(true).Visible(false).Add();
col.Field("Nome").AutoFit(true).AllowEditing(false).Add();
col.Field("Valore").AutoFit(true).Add();
}).AllowPdfExport().AllowExcelExport().AllowPaging().PageSettings(page => page.PageSizes(true)).AllowSorting().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).Toolbar(new List<string>() { "Edit", "Print", "ExcelExport", "PdfExport", "Search" }).Locale(CultureInfo.CurrentCulture.TextInfo.CultureName).ActionComplete("complete").ToolbarClick("toolbarClick").Render())
</div>
</div>
@section scripts{
<script type="text/javascript">
function load(args) {
this.dataSource.adaptor = socAdaptor;
}
}
This is controller:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Administrator")]
public async Task<ActionResult> UpdImpostazioni(ImpostazioniVM value, string action)
{
log4net.Config.XmlConfigurator.Configure();
log.Info("Inizio esecuzione UpdateImpostazioni(ImpostazioniVM value, string action)");
try
{
Impostazione impostazione = _impostazioneRepository.CreateImpostazione();
using (_impostazioneRepository)
{
if (ModelState.IsValid)
{
impostazione.IdImpostazione = value.IdImpostazione;
impostazione.Nome = value.Nome;
impostazione.Valore = value.Valore;
if (await _impostazioneRepository.UpdImpostazione(impostazione) != 1)
{
HttpContext.Response.AddHeader("Exception", Resources.Common.ErroreTrasmissione);
Response.StatusCode = 412;
}
}
else
{
var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
HttpContext.Response.AddHeader("Exception", Server.HtmlEncode(message));
Response.StatusCode = 412;
}
log.Info("Fine esecuzione UpdateImpostazioni(Impostazione value, string action)");
}
}
catch (Exception ex)
{
var message = ex.InnerException == null ? ex.Message : ex.InnerException.Message;
log.Error(string.Format("Errore:{0}", message.ToString()));
HttpContext.Response.AddHeader("Exception", Server.HtmlEncode(message));
Response.StatusCode = 412;
}
return Json(value);
}
This is javascript file:
window.socAdaptor = new ej.data.RemoteSaveAdaptor();
socAdaptor = ej.base.extend(socAdaptor, {
insert: function (dm, data, tableName) {
return {
url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url,
data: JSON.stringify({
__RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
value: data,
table: tableName,
action: 'insert'
}),
contentType: 'application/json; charset=utf-8',
}
},
update: function (dm, keyField, value, tableName) {
return {
type: 'POST',
url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url,
data: JSON.stringify({
__RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
value: value,
table: tableName,
keyColumn: keyField,
key: value[keyField],
action: 'update'
}),
contentType: 'application/json; charset=utf-8',
};
},
remove: function (dm, keyField, value, tableName) {
return {
url: dm.dataSource.removeUrl || dm.dataSource.crudUrl || dm.dataSource.url,
data: JSON.stringify({
__RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
key: value,
keyColumn: keyField,
table: tableName,
action: 'remove'
}),
contentType: 'application/json; charset=utf-8',
};
},
});
This is header:
URL richiesta: https://localhost:44376/it/Administrator/UpdImpostazioni
Metodo di richiesta: POST
Codice stato: 200
Indirizzo remoto: [::1]:44376
Criterio referrer: strict-origin-when-cross-origin
cache-control: private, s-maxage=0
content-length: 91
content-type: application/json; charset=utf-8
date: Thu, 24 Jun 2021 17:16:01 GMT
server: Microsoft-IIS/10.0
x-aspnet-version: 4.0.30319
x-aspnetmvc-version: 5.2
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcU3ZpbHVwcG9cRG9jdW1lbnRpXFByb2dldHRpXEJsb29tQXBwXENvZGljZVxCbG9vbUFwcFxCbG9vbUFwcF9XRUJcaXRcQWRtaW5pc3RyYXRvclxVcGRJbXBvc3Rhemlvbmk=?=
:authority: localhost:44376
:method: POST
:path: /it/Administrator/UpdImpostazioni
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: it,it-IT;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
content-length: 354
content-type: application/x-www-form-urlencoded; charset=UTF-8
cookie: __RequestVerificationToken=8HMj4G-y865qlKc37sllXee-fDZKYS99Uio0RfaVljtaEQAVroM81aXoFTRJ5NyXvFztrKPXzDDpN5OfjZcZBClOmamBIqtwwjbOLnJWDI41; ASP.NET_SessionId=0fxhqdbyzskovyyc14jlp1yq; .ASPXAUTH=CC3977B36C8FD555E147E7B7F285F3DC1870612F50B97459A539A13A1892E74FCFC142CA55079A0B2BFE95CBACD0C88A9AB2BD378E6A84751657562DB221602BECF6AD9D16F33D3474A263A42CE75EFB8EB4E8CF5817A725F548887FD30D26773F9B5772457F1EF423519D4A71C69296C0A1FA5FC7D7587635085B976CB86EBD1B40492C2C54EC4F1C5440449F491E3A
origin: https://localhost:44376
referer: https://localhost:44376/it/Administrator/Impostazioni
sec-ch-ua: " Not;A Brand";v="99", "Microsoft Edge";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.54
__RequestVerificationToken: 7y99YeoYYVHjmhjn9jsYGQhF0kfRrlb-0UpZ4htWaYJyRzzsSt8GjEf3Phd1PF8E2PFI8G62eSmJ_QeiZwGmIaupNsnfgX7St92LUkj1iwi--jhfsriXaCpEsRWCNQ5N0
value[IdImpostazione]: b55e7c78-56ce-43aa-900e-cf2bc8bac4e0
value[Nome]: PortaSMTP
value[Valore]: 465
action: update
keyColumn: IdImpostazione
key: b55e7c78-56ce-43aa-900e-cf2bc8bac4e0
table:
This is response:
{"IdImpostazione":"b55e7c78-56ce-43aa-900e-cf2bc8bac4e0","Nome":"PortaSMTP","Valore":"465"}
This is error:
Thanks for your update.
We have created a new incident under your Direct trac account to follow up with this query. We suggest you to follow up with the incident for further updates. Please log in using the below link.
Regards,
Praveenkumar G
- 7 Replies
- 3 Participants
-
PL Pio Luca Valvona
- Jun 19, 2021 11:02 PM UTC
- Jun 29, 2021 12:49 PM UTC