Search code examples
c#asp.net-mvcasp.net-ajaxantiforgerytoken

ValidateAntiForgeryToken works without Html.AntiForgeryToken()


Ok, this is strange, but... This is my Action code (partly):

[Route(nameof(BackForm))]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> BackForm(BackFormDto model, CancellationToken token = default)
{
    try
    {
        if(!ModelState.IsValid)
        {
            //await Do some
        }
    }

    catch
    {
        // throw some error
    }
}

And this is my View (partly):

 <form asp-controller="Home" asp-action="BackForm" data-ajax="true" data-ajax-method="POST" data-ajax-update="#Search">

    @Html.TextBox("Name", null, new { placeholder = "Name", @class = "form-control mt-1 mb-2" })
    @Html.TextBox("Cont", null, new { placeholder = "E-Mail", @class = "form-control my-2" })
    @Html.TextArea("Txt", null, new { placeholder = "Msg", @class = "form-control mt-2" })

    <input id="btn" type="button" value="Ok" data-bs-toggle="modal" data-bs-target="#myModal" />
</form>

Here, you can see that here is no @Html.AntiForgeryToken() in form. But it works great, Action is working fine and ModelState is valid...

.net8, VS2022, local debug instance

Any ideas?)


Solution

  • Oo... i found. Unexpected from Microsoft

    As written here

    The Form Tag Helper

    Generates a hidden Request Verification Token to prevent cross-site request forgery (when used with the [ValidateAntiForgeryToken] attribute in the HTTP Post action method)

    So starting from net8 you do not need @Html.AntiForgeryToken() any more when usin tag helpers.

    Everything became obvious. Sorry. RTFM)))