razor-pages

How to use send POST request with AJAX in Razor Pages?


I am trying to send a POST request with AJAX but getting status code 400 ("error"). This is my code.

namespace xx.WebApp.Pages.Dependency
{
    public class CreateModel : PageModel
    {        
        public IActionResult OnGet(string test) {

            return Page();
        }

        [HttpPost]
        public async Task<IActionResult> OnPostAsync([FromBody] CreateDependencyRequest createDependencyRequest) {
            return new JsonResult("Test");
        }
    }
}

I troubleshoot it by sending a GET request and it works as expected. I test them by putting a breakpoint at the method.

enter image description here

This is how I send the GET request.

$.ajax({
    url: `/Dependency/Create?test=1`,
    type: 'GET',
    dataType: 'json',                
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});

This is how I send the POST request.

$.ajax({
    url: `/Dependency/Create`,
    type: 'POST',
    dataType: 'json',                
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});

Solution

  • I managed to solve it already.

    I just need to add this line at the program.cs (I am using .NET 6)

    builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    

    and in the form tag, I add the code below which will generate anti-forgery token.

    @Html.AntiForgeryToken()
    

    When you inspect it, you will get something like below:

    <input name="__RequestVerificationToken" type="hidden" value="CfDJ8Hqu8a0DVdlNvQtHk7hhdjABEZXfJ0BowbqYa5n5gr9RoquzRPlAQ42Ye1cqxFfoAy5IWUcOuEgp_GB7QQTM_unQNoSWXo7cdKeNG-1qDI4ygZl0yVyyOKRDufd4SqahvcNz080bisB01SC-GIC2yJLCJkKlEaUtxH6vNpF9wiZxshBBa8ZWopjKrv1sK2Mifg">
    

    and in the Javascript, get the hidden anti-forgery token

    var token = $('input[name="__RequestVerificationToken"]').val();
    

    and add it in the AJAX

    $.ajax({
        url: `/Dependency/Create`,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",token);
        },              
        type: 'POST',
        dataType: 'json',                
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function (data) {
            debugger
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            debugger
            console.log(textStatus, errorThrown);
        },
        complete: function () {
            createButton.prop('disabled', false);
        }
    });