"Troubleshooting a 404 Error with AngularJS PUT Method

I encountered a 404 error when using AngularJS's "$http.put" for a PUT request.

Below is my relevant AngularJS code:

    /* toggles whether or not the link is disabled */
    toggleLinkStatus: function (isActive, linkGUID) {
        $http.put('/Explorer/Link/ToggleLinkStatus',
                {

                            isActive: isActive,
                            linkGUID: linkGUID
                }
        );
    }

Here is the corresponding C# Controller Code:

    [HttpPut]
    public IHttpActionResult ToggleLinkStatus(Boolean isActive, Guid linkGUID)
    {
        return Ok();
    }

And here is my WebApiConfig Code:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        /** define routes for Explorer API */
        config.Routes.MapHttpRoute(
            name: "ExplorerAPI",
            routeTemplate: "Explorer/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

What could be missing here? The Request Payload in the Headers show that the data is being passed through successfully:

isActive: true
linkGUID: "b94badb3-2917-4129-9ae3-35d2a635f66d"

A normal query string PUT using POSTMAN works fine, but not with AngularJS.

UPDATE

An interesting finding is that the following AngularJS request goes through without errors:

    /* toggles whether or not the link is disabled */
    toggleLinkStatus: function (isActive, linkGUID) {
        $http.put('/Explorer/Link/ToggleLinkStatus',
                {
                    isActive: isActive,
                    linkGUID: linkGUID
                },
                {
                    params:
                        {
                            isActive: isActive,
                            linkGUID: linkGUID
                        }
                }
        );
    }

It also works with this modification:

    /* toggles whether or not the link is disabled */
    toggleLinkStatus: function (isActive, linkGUID) {
        $http.put('/Explorer/Link/ToggleLinkStatus',
                {
                },
                {
                    params:
                        {
                            isActive: isActive,
                            linkGUID: linkGUID
                        }
                }
        );
    }

Answer №1

Consider updating the controller action to utilize a class instead of primitive data types. The MVC framework typically expects these values to be extracted from the URI rather than the request body.

Here's an example:

[HttpPatch]
public IActionResult ModifyLinkStatus(LinkRequest input)
{
    // input.IsActive ...
    return Ok();
}

public class LinkRequest {
    bool IsActive {get;set;}
    Guid LinkGuid {get;set;}
}

Answer №2

If you're able to successfully use GET (by entering it into the browser address bar) but are encountering issues with PUT, then there may be a problem with how the route is configured. Although I cannot pinpoint the exact issue in the code snippet provided, it seems like there might be an error in the way your routes have been set up. It's possible that an earlier route is conflicting with the GET request. This isn't a flaw in Angular itself. One way to troubleshoot this is by using the PostMan plugin for Chrome, which allows you to make PUT/POST/DELETE requests in addition to GET requests so you can analyze the outcomes.

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

Having difficulties executing AJAX requests on Codepen.io

My CodePen project that I created 6 months ago is no longer functioning properly. The project includes an Ajax call to retrieve data using jQuery.ajax(). When attempting to load the content from CodePen via https, even though the ajax request is through h ...

Is there a way to transfer a component as a prop to another component in React?

Just began my journey with React and coming from a Java background, please bear with me if the way I phrase this question is not quite right. I'm interested in "passing" an instance of a component to another component (which will then use that passed ...

Props does not solely rely on Vue.js for data feeding

My journey with learning vue has just started, and I recently incorporated a prop into my vue component. At first glance, the code appeared to be correct, but then something unexpected occurred. import Vue from 'vue'; import App from './A ...

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

Instructions for creating a scrollable unordered list when it reaches its maximum capacity

My HTML code has a <ul> element with the following structure: <ul id="messages"> </ul> In my HTML file, I have not specified any <li> items. However, in my JavaScript code using jQuery, I dynamically add <li> items to the & ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

problem encountered when attempting to fetch a value through ajax

Here is an updated version of the code for my preview problem. The goal is to send and retrieve a value using ajax, but I'm encountering issues with sending the value and getting ajax to work properly. This revised code is easier to test on different ...

The process of efficiently uploading a batch of images to Firebase storage while also obtaining all the respective

I have been using firebase storage to upload images and save their respective URLs in the firebase database. However, I recently encountered an issue with my code. In firebase v8, everything was working fine, but after updating to version 9, the following ...

Executing multiple database queries in JavaScript/Node.js without using chaining techniques

I've been experimenting with NodeJS and express for a while now, but I'm stuck on this particular issue. For the product page, my goal is to display: 1) The Product 2) Related Products I want to create reusable code that looks something like ...

Converting a float to a byte array in Unity C# and reading it using Node.js

Looking for help on converting a float value from Vector3.x to a byte array using C# and then decoding it with Node.js. After researching, I found out that Vector3.x is a system.single data type which uses 4 bytes (32 bits). I tried using BitConverter in ...

Implementing JSON Serializer Settings at a Global Scale in ASP.NET MVC

The navigation properties in Entity Framework are causing an exception of "Circular Object Reference" when the collection in my View Model is being serialized by Kendo Grid. Despite setting "ReferenceLoopHandling" to "Ignore" globally in my Application_Sta ...

Is it possible to utilize Javascript instead of PHP Curl to present JSON API data?

After successfully displaying JSON API data from openweathermap.org on my HTML webpage using PHP Curl, I am now seeking help to achieve the same output using Javascript. My PHP script retrieves JSON data from the source, and here is a snippet of that PHP c ...

Is there a way to prevent an HTML5 video from pausing or stopping when scrolling?

At the top of my page, there's a HTML5 video banner with the autoplay and loop attributes. However, when I start scrolling down, the video stops and doesn't resume when I scroll back up. I want the video to keep playing regardless of the user&apo ...

Enabling and disabling contenteditable functionality on a div element in Angular

Issue I am facing an issue while trying to bind a boolean to the contenteditable directive of a div. However, it seems that this binding is not working as expected. Error Message: The 'contenteditable' property is not recognized as a valid p ...

Determine if JSON data is empty using PHP and AJAX

My current code sends a partner-code to a PHP script and retrieves JSON data. $('a.pComment').on('click', function() { var partnercode = $(this).attr('data-code'); if($.trim(partnercode) != '') { $.post(&a ...

Is there a way to convert HTML into a structured DOM tree while considering its original source location?

I am currently developing a user script that is designed to operate on https://example.net. This script executes fetch requests for HTML documents from https://example.com, with the intention of parsing them into HTML DOM trees. The challenge I face arise ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Issue: listen EADDRINUSE - The address is already in use on port 3306

Currently, my project involves creating a logging system using MySQL and Node.JS. Despite my best efforts, I have encountered the error displayed below and have been actively seeking a solution without success. At this point, I have decided to reach out fo ...

The modal window displays an error upon submission and prevents itself from closing

Below is the HTML code for a modal form: <form action="" class="cd-form" method="POST" id="signinform" onsubmit="return: false;"> <p class="fieldset" id="warningPanel"> <?php ShowAlertWarning(); ?> </p> <p ...