Asp.net Core 2.0 Razor Pages Ajax Post
Your URL formation for Ajax request is correct. One thing to note down is, Razor Pages are designed to be protected from (CSRF/XSRF) attacks. Hence, Antiforgery token generation and validation are automatically included in Razor Pages. I believe that is the problem here. Your page may have antiforgery token present on the page if you have form tag in your HTML. But you need to pass the same in your Ajax request.
First, add antiforgery token using @Html.AntiForgeryToken()
, if not present.
Then, modify your Ajax request to send the same in request header.
Like,
beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());},
Read this post Handle Ajax Requests in ASP.NET Core Razor Pages to know more about making ajax request with ASP.NET Core razor pages.
for .net core 2.1 the solution from this blog helped https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/
if the page does not contain form with method post, add antiforgery token @Html.AntiForgeryToken()
and you can start to fire ajax request, important part is to set headers here.
$.ajax({ type: "POST", url: "/Customers?handler=Delete", data: { id: id }, contentType: "application/json; charset=utf-8", dataType: "json", // AntiforgeryToken is required by RazorPages headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() } }) .done(function () { alert("success"); }) .fail(function () { alert("error"); });
By default, Razor Pages are designed to be protected CSRF attacks.
You must properly inject the antiforgery token into your ajax request.
In ASP.NET Core 2.0 it looks like this...
First place this code into the top of your razor view:
// At the top of your page@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf@functions{ public string GetAntiXsrfRequestToken() { return Xsrf.GetAndStoreTokens(Context).RequestToken; }}
Then in your ajax request, set the token header.
$.ajax({ type: "post", headers: { "RequestVerificationToken": '@GetAntiXsrfRequestToken()' }, url: '@Url.Action("Antiforgery", "Home")', success: function (result) { alert(result); }, error: function (err, scnd) { alert(err.statusText); }});