Web API - Unable to retrieve resource: the server returned a status code of 404

Currently, I am working on an AngularJS project with Web API integration.

One of the controllers I have is called Controller/MasterController, and this is configured in my WebApi Config:

HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

To initiate this function, I make a call from Global.asax's Application_Start event.

When calling my web API from service.js, the code looks like this:

var service = function ($http) {
    var _$http = $http;
    self = this;
    self.getMenuItems = function () {
        var promise = _$http({
            method: "GET",
            url: 'api/Master'
        }).success(function (data, status, headers, config) {

        }).error(function (data, status, headers, config) {

        });
        return promise;
    };

While debugging, I noticed that I reach this particular section. However, the Chrome console displays this error message: "Failed to load resource: the server responded with a status of 404"

The requested URL was:

http://localhost:12345/api/Master

Moreover, attempting to access the web API controller directly through the browser has been unsuccessful for me.

Thank you for your assistance.

Answer №1

To confirm that your API is functioning correctly, you can perform the following steps:

Ensure the following code is in Global.asax.cs:

public class WebApiApplication : HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

In the WebApiConfig file:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Create a MasterController with the following code:

using System.Web.Http;

namespace WebApi.Controllers
{
    public class MasterController : ApiController
    {
        public string Get()
        {
            return "Hello world";
        }
   }
}

Accessing http:// localhost:[SomePort]/api/Master in your browser should display: "Hello world"

The configurations provided are standard for initializing a new WebApi.

Answer №2

Exploring different paths led me to uncover fresh insights. Discover the resolution for the last error encountered here

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

Utilizing Social Media Sharing Functionality in Ionic with Cordova Plugins

Currently, I am working on incorporating social sharing functionality in my Ionic project. I followed a tutorial available at However, I encountered an error which states: TypeError: Cannot read property 'socialsharing' of undefined at Object. ...

Whenever I try to import a function, I encounter the error message "no exported member."

I am facing an issue with my node/typescript application where I am attempting to import a function from another file. In order to export it, I utilized exports.coolFunc = coolFunc, and for importing, I used import {coolFunc} from '../controller/coolS ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...

Angular: Discovering and retrieving all images within a div container

I am on a quest to locate all image tags within a specific div. These image tags are nested within paragraph tags inside the div. I attempted to create a plunkr to accomplish this task, but unfortunately, I haven't had any success yet. If anyone is ab ...

How to display a variety of JSON data in different templates with unique variables using angularjs

I am curious about the best approach to handling a response that contains various types of objects presented like this: [ {"nodeClass":"Entity", "text":"foo","entityfield":"booz"}, {"nodeClass":"User","username":"bar","userfield":"baz"} ] Each type of ob ...

Prevent the use of punctuation marks like full stops and commas in GridView Textbox

Within my GridView, there is a column that contains a textbox: <asp:GridView style="width:75%;float:left" ID="gvPieceOutturns" ShowHeaderWhenEmpty="false" CssClass="tblResults" runat="server" OnRowDataBound="gvPieceOutturns_I ...

Encountering the error message "do not mutate props directly" while also trying to render a button

Whenever I try to pass my prop to a component, I encounter an error message. The prop in question is used to display a button element in the payment section. However, there are certain components where this button should not be displayed. Unfortunately, wh ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

Issue with node.js server functionality on Azure Cloud Services virtual machine

I am currently exploring node.js and experimenting with creating a basic node js server that functions properly on my local machine. Here is an example of the "Hello World" code: var http = require('http'); http.createServer(function (req, res) ...

The task "gulp js src - duplication and implementation of base" involves duplicating

My gulp task is set up to copy JavaScript files. The initial setup below did not work: gulp.src('./**/*.js', {base: '../src/main/'}) .pipe(gulp.dest('../target/dist')); After making some adjustments, the following code ...

Having trouble with Javascript Array Push and Splice not functioning properly?

My goal is to replace the value "3" with "4" in the array. After this operation, only "1":"2" will remain in the array. const array = []; array.push({ "1": "2" }) array.push({ "3": "4" }) const index = array.indexOf(3); if (index > -1) { array.sp ...

Having difficulty retrieving controller scope in the view

I am having trouble accessing the scope "$scope.historySelectionFieldValues" in my directive's controller. It does not seem to be populated. Here is my view: View <ji-select-box ng-repeat="{{historySelectionFieldValues}}"></ji-select-box> ...

What could be the reason for receiving no file input after submitting the form?

One of the functions triggers the input file and displays previews: $(document).on("change", "#Multifileupload", function() { var MultifileUpload = document.getElementById("Multifileupload"); if (typeof FileReader != & ...

Creating dynamic charts using a factory pattern

I'm working on dynamically adding charts to a widget based on a selection from a combobox. To achieve this, I've implemented the factory pattern. Here's the backend code snippet: public interface ICharts { string chartType ( ...

You are unable to establish headers once they have already been sent to the client, as indicated by the error

Github : https://github.com/UJJWAL2001/Pro-Shop/tree/main/backend My current objective is to implement JWT token for securing my routes using the middleware provided below import jwt from 'jsonwebtoken' import User from '../models/userModel ...

What is the best way to pass a form result from a parent component to a child component

In the setup, there is a child component containing a form with various options for selection. The goal is to capture the user's selection and process it within this child component. Despite attempting to utilize an event in the parent component, the ...

Working with JSON data retrieved from a PHP and MySQL backend in an AngularJS application

Having difficulty handling the JSON response from PHP. I am using AngularJs to display the received JSON data. As a newcomer to Angular, I attempted a basic exercise and would appreciate some assistance. Thank you in advance. index.html <!DOCTYPE HTML ...

Methods for dynamically inserting data into a JSON structure

I have created a form where I input data and send it via AJAX 'post' to MySQL. On the same page, there is another AJAX request which is a 'get' method used to retrieve data and display it in a table. My query is: Is it possible to dynam ...

The Angular Material md-menu element stubbornly refuses to close when clicked outside, especially if the target element has a fixed position and

I currently have a <md-menu> element implemented in my webpage. By default, the menu will close if clicked anywhere on the page. However, I have noticed that when clicking inside a fixed element with a specified z-index, the menu does not close. < ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...