Angular: HttpClient Post Request not hitting the Asp.net MVC Controller's Action Method

Viewed 84

I'm new to Angular Development! Here I'm developing a sample angular project. From this Angular Sample, I have to make HTTP calls to the ASP.NET MVC Web Application. I have to connect to the MVC's Controller Action Methods.

Initially, I created an angular application using CLI.

Then I created a new component using ng generate component ComponentName

Here My component name will be MaterialList

Material List Component:

import { Component, OnInit } from '@angular/core';
import { TestService } from '../testservice.service';

@Component({
    selector: 'app-material-list',
    templateUrl: './material-list.component.html',
    styleUrls: ['./material-list.component.css']
})
export class MaterialListComponent implements OnInit {
     sites: any = [{ Id: 0, Name: 'TMD | Texas  Machinery Depot' }];

     constructor(private testServ: TestService ) { }

     ngOnInit() {
       this.testServ.SignInToHMIDS().subscribe(login => {
           if (login) {
            console.log("Login Success");
           } else {
            console.log("Login Failed");
         }
      }, (err) => {
           console.log(err.message);
      }, () => {
         console.log('completed');
     });
      this.testServ.LoadMaterialListPage().subscribe(result => {
         var listData = JSON.stringify(result);
         console.log(listData);
      }, err => {
         console.log(err.message);
      }, () => {
        console.log('completed');
     });
  }

 }

Material List Html file:

<h1>Material Search</h1>
 <div class="row">
    <div class="col-md-3">
        <div class="form-group">
            <label style="font-weight:bold">Site</label>
            <select class="form-control" id="pCategory" name="pCategory">
            <option *ngFor="let s of sites" value={{s.Id}}>
                {{s.Name}}
            </option>
            </select>
        </div>
    </div>
    <div class="col-md-4">

    </div>
  </div>

And Also, I have added a Service using ng generate service serviceName

Here my Service name is TestService

TestService.ts:

 import { Injectable } from '@angular/core';
 import { HttpClient, HttpHeaders } from '@angular/common/http';
 import { SignInModel } from '../app/Models/RequestModels';

  @Injectable({
    providedIn: 'root'
  })
export class TestService {
    public _hmidsLoginUrl: string = 'http://localhost:58861/Api/AuthorizationService/SignIn';
    public _materialListUrl: string = 
   'http://localhost:58861/Api/MaterialService/MaterialListOnPageLoad';

   constructor(private http: HttpClient) {

   }
   SignInToHMIDS() {
        var requestData = JSON.stringify({
           UserName: "test.u.login1.txt@mail.mil",
           Password: "TEST4587",
           NewSignIn: false,
           RememberMe: false
    });
    return this.http.post<SignInModel>(this._hmidsLoginUrl, requestData, {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Allow-Methods':'GET, POST, OPTIONS, PUT, DELETE'
          })
       }
     );
  }
 LoadMaterialListPage() {
      return this.http.get<any>(this._materialListUrl);
 }
}

And my Request Model Class is given below

export class SignInModel {
    UserName: string;
    Password: string;
    NewSignIn: boolean;
    RememberMe: boolean;
}

When I try to Connect the Angular POST Calls to the MVC Project, I have faced the No Access-Control-allow-origin Cors Issue. To Resolve this, I have followed the below steps

I have installed the Microsoft.AspNet.WebApi.Cors package to the ASP.NET MVC Project.

Then I have added the below Code in the WebApiConfig.cs file. Inside the "Register" Method

config.EnableCors();

And then I added the "EnableCors" Attribute above the MVC Controller's name

SignIn Controller and Action:

 [EnableCors("*", "*", "*")]
 public class AuthorizationServiceController : ServiceBase

MaterialList Page controller and Action

[EnableCors("*", "*", "*")]
[Authorize]
public class MaterialServiceController : ServiceBase

After Configuring Above all, I have been facing these issues in the Angular Project Console

  1. Http failure response for http://localhost:58861/Api/MaterialService/MaterialListOnPageLoad: 0 Unknown Error
  2. GET http://localhost:58861/Api/MaterialService/MaterialListOnPageLoad net::ERR_CONNECTION_REFUSED
  3. Http failure response for http://localhost:58861/Api/AuthorizationService/SignIn: 0 Unknown Error
  4. POST http://localhost:58861/Api/AuthorizationService/SignIn net::ERR_CONNECTION_REFUSED

The Angular Project Output with Console Error is given below

Angular Project Console Errors



Note:

  1. In My MVC Project, once the user login into the application, he is allowed to access the other screens.
  2. From this Case, Initially Sign In and then Material List API Calls are made from the angular project.


Any Help Related to the above Will be more helpful for me?

0 Answers
Related