Creating a dynamic web application using Asp .NET Web Api, MVC, and Angular 2, integrating an action that

Working on an ASP .NET MVC application integrated with Angular 2, I encountered a problem when trying to communicate from the angular service to a WebApi Controller. The issue arises when attempting to access an action within the WebApi Controller that requires two parameters.

Despite thorough research on similar questions, the problem persists. I have ensured that my webApi routes are registered before the MVC ones and can successfully access the action if no parameters are needed. However, when trying to hit it with specific parameters, I consistently receive a 404 not found error for the Login action - POST localhost:12312/api/userapi/login 404 (Not Found).

I have experimented with various formatting options in the WebApiConfig, including optional parameters, dynamic controller placeholders, and exact names for actions and controllers. I also tried using the Routing attribute without any success.

Another attempt involved defining a single parameter "object credentials" and adjusting the WebApiConfig.cs, but unfortunately, the outcome remained unchanged.

RouteConfig.cs

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",
            defaults: new { controller = "Home", action = "Index", id = 
                     UrlParameter.Optional }
        );

WebApiConfig.cs

       config.MapHttpAttributeRoutes();

       config.Routes.MapHttpRoute(
            name: "api",
            routeTemplate: "api/userapi/login/{username}/{password}",
            defaults: new { username = RouteParameter.Optional, password = 
            RouteParameter.Optional }
        );

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

UserApiController.cs

    [HttpPost]
    public HttpResponseMessage LogIn(string username, string password)
    {
        return ToJson(userRep.LogIn(username, password));
    }

angular

this.http.post(url, JSON.stringify(credentials), { headers: headers })
            .subscribe(res => {
                resolve(res.json());
            }, (err) => {
                reject(err);
            });

Answer №1

It's puzzling why the approach using parameters isn't working for you, but I'll show you how to create a model in a different way.

public class LoginModel{
    public UserName {get;set;}
    public Password {get;set;}
}

Then in the login method:

[HttpPost]
    public HttpResponseMessage LogIn(LoginModel model)
    {
        return ToJson(userRep.LogIn(model.username, model.password));
    }

You don't need custom routing, just stick to the default configuration.

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

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

"Attempting to access a Service in Angular before it has been initialized is

When I try to run tests, they fail right at the beginning with an error message: Chrome 83.0.4103.61 (Linux x86_64) ERROR An error was thrown in afterAll Uncaught ReferenceError: Cannot access 'SomeService' before initialization ReferenceE ...

Incorporate Lodash into your Angular2 project within Visual Studio 2015

I've been attempting to incorporate the lodash dependency into my project, but I keep encountering issues during the VS2015 build process. The error message in the build output states "Build: Cannot find module 'lodash'", causing the build t ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

Observable<Any> Filter

I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...

Access the $event object from an Angular template selector

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <input type="file" #myFile multiple /> <button (click)="onDelete(myFile.event)">DeleteFiles</button> My code snippet is experienci ...

"Implementing middleware controls for email duplicates can prevent poorly designed code structures

I'm looking to implement a node.js express middleware for controlling duplicate emails, and I need a simple and concise code snippet for this. Here is the code from my middleware.js file: // ----------------------------------- MIDDLEWARE FUNCTION ...

Setting a default value and object ID in Angular's reactive forms for a select dropdown

Having an issue with validating a default value in a selector that serves as a message to select an option. The problem arises from the validation of this option, as it is linked to the object ID of another collection in the database (mongoose-express js). ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

Guide on updating a property key in Firebase real-time database with Angular 7

Is it possible to modify the key of a property in my firebase database that I have been struggling with? ...

Ways to troubleshoot this issue: encountering error in Angular v11 - The Schematic workflow has encountered a failure

I keep encountering an error whenever I try to generate a new project Command I used: ng new dron (to create the project) Error message: npm ERR! Found: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1767786463746464572f39253 ...

Transfer information to a form using the <mat-select> element

Looking for a way to display user roles in Angular using a mat-table that were previously selected with <mat-select>. When I use a regular <select>, a new entry shows up in the table, but the styling is not ideal. <label>Role</labe ...

Issues with Angular routing after upgrading to Angular 4

After making updates in this way, they can be found here To update on Linux/Mac: run the command npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest type ...

Is there a way to set up the application that consumes an npm module with a private git url to strictly utilize files exclusively from the module's dist folder?

In my angular application, I encountered an issue with angular-cli not supporting the creation of a library. To work around this, I opted to use the popular git project found at https://github.com/jvandemo/generator-angular2-library for creating my library ...

Reactive form enabled for Angular control

In order to meet the required format for a social security number input field using reactive forms, it must adhere to the following conditions: The format should be ###-##-####. Limited to 9 digits without including the dashes (11 characters with dashes) ...

Leverage Angular2 components within Angular4 framework

Would it be possible to utilize angular2 components in angular4 projects? Specifically, I am interested in using a chart generation library from . However, it seems that the dependencies of this library are not compatible with my application. Are angular2 ...

Issues arise after upgrading Node and npm, causing an inability to execute any npm command

Following an upgrade to the latest Node and npm version, I encounter an error when attempting any npm command: C:\Users\...>npm doctor TypeError: Cannot read property 'prefix' of undefined at parseField (C:\Users&bs ...

What is the best approach for transferring non-string objects between routes in Angular?

I am currently developing a custom file viewer. To achieve this, I have created a specialized component known as FileBrowserComponent that is specifically designed to be displayed when the route /files is accessed. When navigating, I include a query param ...

How to access data within nested objects using ngFor in Ionic 4

How can I access the data I need from an API when it is nested within multiple objects? I am attempting to retrieve the full_url from the data object, which is nested inside the avatar object. I have already attempted the following: <ion-list> ...