Use AntiForgeryToken only with fetch in my project on .NET Framework

27 Views Asked by At

I want to use AntiForgeryToken technology to post data to my controller with the fetch promise of Javascript (not ajax).

It works without AntiForgeryToken if I add the attribute

[HttpPost, ValidateInput(false)] 

above my action (see below).

Now I want to use AntiForgeryToken. I tried sending in my FormData the token __RequestVerificationToken with its value and put the attribute

[HttpPost, ValidateAntiForgeryToken] 

on the action, but it did not work.

I added the header X-ANTI-FORGERY-TOKEN in my FormData but it did not work, either.

Some post on this site are about this issue but with but for ASP.NET Core platform.

Any idea? Thank you for the attention

Client side (in my js function):

f = new FormData();
txtBody = 'Hello ';  
f.append('txtBody', txtBody);
url='http:/....';

fetch(url, { body: f, method: "post" })

    .then(response => {
        //console.log('la reponse');
        //console.log(response);
        a = response.text(); return a
    })
    .then(t => {
        //console.log('le final');
        //alimente le body du modal
        alert(t);
         
    }); 

Server side (Controller)

[HttpPost, ValidateInput(false)] 
public ActionResult Doing (FormCollection fc)
{
    string txt = fc["txtBody"].ToString();

    // logic

    return Content("OK");
}
0

There are 0 best solutions below