Home > Blockchain >  AJAX POST request returns 404 .NET 6
AJAX POST request returns 404 .NET 6

Time:12-20

I have this issue:

I am using .NET 6 with MVC and I am making use of FullcalendarIo. I have a controller for making free slots in the calendar. This is the code in the controller:

 [Authorize(Roles = DoctorRoleName)]
 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task < ActionResult < AppointmentSlotInputModel >> GenerateSlots(AppointmentSlotInputModel model) {
     //await this.appointmentService.GenerateSlots(model.Start, model.End, model.SlotDurationMinutes);
     return Json("Hello");
 }

And this is my JS Code that makes the POST request

const params = {
    start: startDate,
    end: endDate,
    slotDurationMinutes: scale
};

const response = await fetch('/Appointment/GenerateSlots', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'RequestVerificationToken': document.getElementById("RequestVerificationToken").value
    },
    body: JSON.stringify(params)
});

In the network tab the request to /Appointment/GenerateSlots I get first code 302 - Redirect and then 404 Not Found. The request url seems correct - https://localhost:44376/Appointment/GenerateSlots.

f I change the method to GET and put the [HttpGet] attribute above the action in the controller I get the JSON result. In the Startup.cs I am using these:

    services.AddAntiforgery(options => {
        options.HeaderName = "X-CSRF-TOKEN";
    });

    services.Configure < CookiePolicyOptions > (options => {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

But event if I comment them out the result is the same - first 302 then 404. I have tried a lot of the code that is written here on the site for people with similar issues, but it hasn't helped. Where am I mistaking? I am using standard routing:

app.UseEndpoints(endpoints => {
    endpoints.MapControllerRoute(
        name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Edit: I have found a similar thread here - ASP.NET controller, AJAX GET works, but POST does not (404) But this doesn't seem to be the case for me.

CodePudding user response:

So I found a my solution. In my Startup.cs I have this code:

    services.AddAntiforgery(options =>
    {
        options.HeaderName = "X-CSRF-TOKEN";
    });

And the BadRequest from the Controller came because of the AntiForgeryToken validation. In my AJAX call my header for the AF Token was wrong: It was 'RequestVerificationToken', but it should have been 'X-CSRF-TOKEN' or the other way around. But still now I have the proper result and no more BadRequest.

  • Related