Reputation: 4076
I'm running into an issue I don't quite understand.
asp.net core 2.2.1 using razor pages, I'm having to manually generate the antiforgery token but all the documentation seems to claim that isn't necessary with razor pages.
Any insights as to what I'm doing wrong here?
If you remove the @Html.AntiForgeryToken() from the below form then the token isn't added. If this is what you're supposed to do that's great, I'm done, but every source I can find seems to think this isn't necessary.
<form method="post">
@Html.AntiForgeryToken()
<div>Source Type: <input asp-for="filter.SourceType" value="JsonEvent"/></div>
<div>Source Name: <input asp-for="filter.SourceName"/></div>
<input type="submit"/>
</form>
Upvotes: 2
Views: 8116
Reputation: 149
Dont forget to use TagHelpers in your razor pages.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
This is a valid HTML syntax both in native HTML and using TagHelpers, but form will do the anti forgery magic only if its a TagHelper.
<form method="post">
<input type="email" name="userName" />
<input type="text" name="password" />
<button type="submit">Save</button>
</form>
I've run into this adding Razor pages to an originally Web Api project.
Upvotes: 0
Reputation: 91
You absolutely do not need to use code like @Html.AntiForgeryToken()
within your form element in order to generate an AntiForgeryToken when you are using ASP.NET Core Razor Pages. The token is generated and submitted automatically when you submit your form.
You can validate this idea by checking your Browser's development tool section. You can inspect the headers and you will see a Form Data "_RequestVerificationToken" as shown in this screenshot.
But, note that, your Ajax requests are different. For example, if you use jQuery Ajax method to post to any of your Razor page's Post handler, then you will need to generate the token explicitly and pass the header along with your request.
Upvotes: 5
Reputation: 1446
As per the Documentation, @Html.AntiForgeryToken()
does not need to be added as the markup you used should be enough:
<form method="post">
...
</form>
I would check that the token isn't set at the bottom of the form as outlined in this article
Upvotes: 2