.NET 6 shows 404 error on AJAX POST request

I am encountering an issue with my code:

Currently, I am utilizing .NET 6 with MVC and integrating FullcalendarIo. I have a controller specifically for creating free slots in the calendar. Below is the snippet of code from 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");
 }

Moreover, here is the JavaScript code responsible for making 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)
});

Upon inspecting the network tab, when sending a request to /Appointment/GenerateSlots, I receive a 302 - Redirect followed by a 404 Not Found error. The URL of the request appears correct - https://localhost:44376/Appointment/GenerateSlots.

If I switch the method to GET and include the [HttpGet] attribute above the action in the controller, I successfully obtain the JSON result. In my Startup.cs file, I have configured the following:

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

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

Despite trying various solutions suggested on similar threads, such as one found here - ASP.NET controller, AJAX GET works, but POST does not (404), I have yet to resolve the issue. Any insights on where I may be going wrong?

I am employing 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?}");
});

Answer №1

After some troubleshooting, I finally resolved the issue. Upon reviewing my Startup.cs file, I discovered the following code:

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

The reason for the BadRequest response from the Controller was due to AntiForgeryToken validation. It turns out that in my AJAX call, the header for the AF Token was incorrect – It was 'RequestVerificationToken' instead of 'X-CSRF-TOKEN' (or vice versa). Once I corrected this mistake, everything worked as expected without any more BadRequest errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to detect when the escape key is pressed?

Is there a way to detect when the escape key is pressed in Internet Explorer, Firefox, and Chrome? I have code that works in IE and alerts 27, but in Firefox it alerts 0 $('body').keypress(function(e){ alert(e.which); if(e.which == 27){ ...

The drag functionality can only be used once when applied to two separate div elements

Recently, I came across an issue where I have both an Image and a custom text element placed between them using an input box. My goal is to make both the text and the image draggable on the page. However, I noticed that while the image can be dragged and d ...

Selenium: Do By.Id("myelement") and By.Css("#myelement") have varying levels of performance?

As I was developing some helper functions for our testers using the IWebDriver in .NET, I couldn't help but question the necessity of having a method specifically to retrieve an element by its ID when CSS selectors can achieve the same result. I assu ...

Can anyone suggest a more efficient method for detecting expired SESSIONS in JQuery?

After only a few weeks of using JQuery, I've encountered an issue where my login page loads within the existing document when the SESSION expires. This problem never occurred before I started using JQuery. It seems that since I have converted all my d ...

Missing GetServer in C# MongoDB.Driver - What's the Next Step?

Referencing the mongoDB.Driver documentation (http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-csharp-driver/) Obtaining a Server Reference To obtain a reference to a server object from the client object, use the following code: var server ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

Is there a way to send the id to the print page within the ajax success function?

https://i.stack.imgur.com/SGAAT.jpg The image above shows the selection of 3 records with MR No 7, 8, and 9. These selected records were successfully inserted into my database. Now, I need to retrieve these IDs in the ajax success function to pass them to ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

eliminate item from list upon user clicking the button

Does anyone have any tips on how to effectively store and remove user-selected items from an object in JavaScript? I'm encountering an issue where only the first object in the array is being removed, and not the others. Any help would be appreciated! ...

Click event for nodes in a d3js tree layout

My current project involves utilizing the d3js tree layout to showcase an interactive tree structure on the screen. Is there a comprehensive tutorial or detailed documentation available for effectively implementing the d3js tree layout? Furthermore, I ai ...

Tips for establishing a connection with a browser that is already open

Can someone provide a step-by-step guide for connecting to an existing open browser using Selenium Webdriver with C#? This problem is consuming a significant portion of my time spent developing scripts! ...

How Jquery's Ajax can terminate SQL processes in PHP

Currently, I have a script that reads a .CSV file line by line and inserts the data into a database using an "INSERT QUERY". I am looking for a way to allow the user to stop this script at any given time. Below is my AJAX call: postselect = $.post(&apos ...

Storing the values of a React JS application in local storage using

Storing data received from the backend in local storage: async onSubmit(e){ e.preventDefault(); const {login, password } = this.state; const response = await api.post('/login', { login,password }); const user ...

"Enhabling the ability to select by ColumnHeader, RowHeader, and Cell within a DataGridView

I am currently working on adding an Excel-like feature to my DataGridView. Here's what I need it to do: If the user selects a column header, it should select the entire column When they select a row header, the entire row should be selected Additio ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Angular JS: using data binding with dynamically inserted html elements

I'm currently experiencing difficulties with two-way data binding in AngularJS. I have provided a sample code snippet below: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular ...

Capture the item selected from the dropdown using ng-model to retrieve the name instead of the

I need help getting the name/text/html of the selected option in a dropdown using angular.js, rather than just its value. Currently, I have this setup which retrieves the value: Here is my HTML code snippet <select class="SelectCar" ng-model="Selected ...

What is the best way to store HTML in a variable as a string?

Imagine if I have a variable: let display_text = "Cats are pawsome!" I aim to show it as such: <div> <b>Cats</b> are pawsome! </div> To be clear, dynamically enclose the word "cats" whenever it shows up. ...

Ways to compel a JSON-transmitted expression into the Angular scope

Seeking guidance on the best way to convert HTML from JSON into a trigger for a modal/toggle upon clicking. Within the JSON data consisting of 100 entries, there are about 10 links that need to activate a pop-up when clicked. These links are displayed as ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...