AngularJS failing to trigger Web API Route configuration with multiple parameters

Hello, I am facing an issue with my WebApiConfig, API Controller, and Angular Service. The 1st route is working perfectly fine, but the 2nd and 3rd routes are not being called by AngularJS even though the web API route seems to be correct.

--WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.Formatters.Remove(config.Formatters.XmlFormatter);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{param}",
            defaults: new { param = RouteParameter.Optional }
        );
        
        config.Routes.MapHttpRoute(
            name: "Api2",
            routeTemplate: "api/{controller}/{action}/{param1}/{param2}",
            defaults: new { param1 = RouteParameter.Optional, param2 = RouteParameter.Optional }
        );
        
        config.Routes.MapHttpRoute(
            name: "Api3",
            routeTemplate: "api/{controller}/{action}/{param1}/{param2}/{param3}",
            defaults: new { param1 = RouteParameter.Optional, param2 = RouteParameter.Optional, param3 = RouteParameter.Optional }
        );
    }
}

--Web API Controller

[HttpPost]
public IHttpActionResult InsertAcademicInfo(AcademicInformation[] param1, AcademicResult[] param2)
{
     return Ok(_academic.InsertAcademicInformation(param1, param2).Data);
}

--Angular Service

mainApp.factory('AcademicServices', ['$http', '$rootScope', function ($http, $rootScope) {
  return {
    Save: function (academic, results) {
        return $http({
            url: '/Api/ApiAcademic/InsertAcademicInfo',
            method: 'POST',
            data: { param1: academic, param2: results },
            async: false
        });
    },
  };
}]);

Answer №1

It seems like there may be a misunderstanding of how the post method works in Web API. The data you are sending does not seem to match your expectations. To send data via the message body, you should be sending a single object, which can be complex. This is different from what you are currently doing in your angular/javascript call. You may need to update your web api method to handle this correctly.

In addition, consider using route attributes instead of creating a large routing table to handle all routes. Utilize RouteAttribute and RoutePrefixAttribute. You do not need parameters in the method below as the data is sent in the request's message body rather than the URI.

AcademicInfoModel.cs

public class AcademicInfoModel {
    public AcademicInformation[] param1 {get;set;}
    public AcademicResult[] param2 {get;set;}
}

ApiAcademicController.cs

[RoutePrefix("api/ApiAcademic")]
public class ApiAcademicController : ApiController
{

    [HttpPost]
    [Route("InsertAcademicInfo")]
    public IHttpActionResult InsertAcademicInfo(AcademicInfoModel model)
    {
         return Ok(_academic.InsertAcademicInformation(model.param1, model.param2).Data);
    }
}

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

Retrieve a formatted Word document from a C# endpoint to a Node.js server

I am currently facing an issue with my Node.js server that sends a GET request using axios to a C# endpoint with JSON as a parameter. The C# API then uses Newtonsoft.Json to deserialize the JSON, reads a Word file into memory, and inserts data. The final s ...

Creating blank entities with app.post using AngularJS and mongoose in a node.js environment

My issue seems to be with my REST API as it is posting empty objects. The value I am retrieving from req.body.name appears correctly when I log it using console.log(req.body.name);. POST: { name: 'typing any name', status: null } typing any na ...

Error message encountered in MEAN application request

Learning how to use the MEAN stack has been an exciting journey for me as I venture into building web apps. Rather than relying on yeoman generators or npm app to do the heavy lifting of generating code, I have delved into creating my entire app from scrat ...

Use `Res.download()` to send data to the client instead of directly downloading the file

I am trying to transfer a file that has been created by my NodeJS server from the server to the client for download. Users input object data which is then stored in a database. The function responsible for creating the file will read these objects and pop ...

Node.js and Express.js are being used in conjunction with Angular to create a server-side controller that fetches all data. However, there seems to be an issue as the

"findByStaff" and "findOne" are working correctly, however, "findAll" is not returning any data. I expected findAll to retrieve all courses from mongodb $scope.findByStaff = function() { $scope.courses = Courses.query(); }; $scope.fin ...

Dealing with a Nodejs/Express and Angular project - Handling the 404 error

Recently, I decided to dive into learning the MEAN stack and thought it would be a great idea to test my skills by building an application. My goal was simple: display a static variable ('hello') using Angular in the HTML. However, I ran into an ...

Exploring MeanJS through the WebStorm debugger

Currently, I am in the process of developing a node/angular application using the MeanJS project as my foundation. One particular issue that I have encountered involves the grunt file included in MeanJS, which executes a series of tasks prior to initializi ...

Having issues with installing <package> using npm

I'm currently following a tutorial to install the Angular package in my project. My system already has npm (4.0.5) and node (6.9.2) installed. I navigated to my project folder and executed the following command: npm install angular Despite runnin ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...

Creating a node server that will intercept all requests from an Angular frontend (using http) and route them to a

Currently, I am utilizing express on node for routing and incorporating Angular as the front-end framework. Additionally, Redis is being used for session management. My objective is to ensure that whenever an HTTP request is made from Angular, it first goe ...

Unfortunately, despite attempting to kill all processes linked to port 4200, it seems that it is still in use

Getting angular up and running on my Mac OS X 10.11.3 El Capitan has been quite a challenge. After installing nodeJS and npm, I used npm to install angular-cli. To create a new app, I executed the command sudo ng new first-app Then, I navigated into the ...

Leveraging AngularJS and PhoneGap for seamless Facebook login/SDK integration even without the need for a server

In the process of developing a web application that will be deployed with Phonegap, I am utilizing NodeJS on the backend and AngularJS on the frontend, incorporating Facebook authentication. Currently, the Node server is running at localhost:3000 (will eve ...

Differences between String Comparison in Node.js with "UTF-16"

Just starting out with Node.js and hoping to find an npm package or module that can compare two strings in UTF-16 format. In my C# code, I currently use the following function: public int Compare(string x, string y) { var myComparer = CompareInfo.Get ...

NodeJs causing issues with reloading AngularJs routes

I was able to successfully create a sample app by following a few examples, but I've encountered an issue that I'm struggling to resolve. In my Angular app, the routes work fine like this: - http://localhost:8888/#/login works However, when I re ...

Ways to store a filestream coming from Node.js into AngularJS

When using my express server, I have a post-request set up to retrieve a pdf file from Amazon S3 and then send it back to Angular. This is the endpoint in my express server: var fileStream = s3.getObject(options).createReadStream(); fileStream.pipe(res); ...

Optimizing JavaScript performance by packaging files with Browserify

Currently, I am utilizing AngularJS for the front end of my project. Initially, I was using Grunt as my build tool but now I am interested in transitioning to npm for this purpose. I came across a useful link that discusses using npm scripts as a build too ...

AngularJS: Where server-side templating meets modern web development

I am a beginner in the MEAN stack and recently developed an application using node.js, express, and mongodb. I would like to pass the username to the dashboard once the user logs in. How can I achieve this using AngularJS without relying on the ejs templat ...

What is the method to access the controller value within a metadata tag?

One of the challenges I am facing is how to access a variable from a controller and use it in a metadata tag using AngularJS. Below is my approach: First, let's define the variable in the controller: app.controller('homeCtlr', function($sc ...

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...