I'm working on a combined .Net Core 3.1, Angular 8 project.
The Angular code is embedded inside the Visual Studio project that contains the MVC code, under a ClientApp folder
I'm fine with .Net but Angular is new to me as of 2 days ago.
I'm trying to get the Angular code to call an MVC API
I've been following a number of videos and tutorials and I came up with this as a sort of proof of concept.
Angular Code
import { Component, OnInit } from "@angular/core";
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'people-list',
templateUrl: "peopleListView.component.html"
})
export class PeopleListView implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
let test = "";
test = "/api/Person/GetPeopleList";
this.http.get(test).subscribe((data: any) => console.log(data), (err: any) => console.log(err));
}
MVC code
[ApiController]
[Route("api/[controller]")]
public class PersonController : Controller
{
public PersonController()
{
}
[Route("api/[controller]/[action]")]
[HttpGet]
public List<Person> GetPeopleList()
{
List<Person> people = new List<Person>{
new Person{Id = 1, Name = "Scott"},
new Person{Id = 2, Name = "Bill"}
};
return people;
}
}
I can see that the break point on the Angular code get hit so my Angular code before that is functioning but the GetPeopleList() method is not hit and I'm getting a 404 error.
I've tried a number of variation on the route e.g. [Route("api/[controller]]")] but to no avail.
Where have I gone wrong?
UPDATE
Having seen that my code is requesting localhost:5001/api/Person/GetPeopleList
I am wondering if the API is actually on port 5001 as that is controlled by the Angular app.
CodePudding user response:
you have to fix a route by adding "~/" to the start. It means that route starts from the route, your current route needs ".../api/person/api/person/getPeolelist" url
[Route("~/api/Person/GetPeopeList")]
public List<Person> GetPeopleList()