我正在研究一個組合的 .Net Core 3.1,Angular 8 專案。
Angular 代碼嵌入在包含 MVC 代碼的 Visual Studio 專案中,位于 ClientApp 檔案夾下
我對 .Net 很好,但 Angular 2 天前對我來說是新的。
我正在嘗試讓 Angular 代碼呼叫 MVC API
我一直在關注一些視頻和教程,我想出了這個作為一種概念證明。
角碼
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代碼
[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;
}
}
我可以看到 Angular 代碼上的斷點被擊中,所以我之前的 Angular 代碼正在運行,但是 GetPeopleList() 方法沒有被擊中,我收到了 404 錯誤。
我在路線上嘗試了許多變體,例如 [Route("api/[controller]]")] 但無濟于事。
我哪里錯了?
更新 看到我的代碼正在請求 localhost:5001/api/Person/GetPeopleList
我想知道 API 是否真的在埠 5001 上,因為它是由 Angular 應用程式控制的。
uj5u.com熱心網友回復:
您必須通過在開頭添加“~/”來修復路線。這意味著路由從路由開始,你當前的路由需要“.../api/person/api/person/getPeolelist” url
[Route("~/api/Person/GetPeopeList")]
public List<Person> GetPeopleList()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375781.html
標籤:有角的 asp.net-mvc
