我是 Angular 和 WebApi 新手。
我想使用 webApi 调用检索数据。
我正在尝试调用 Api 方法并从角度服务传递 id。
下面是服务。
retrieve-data.service.ts
GetBatchDetailsById(batchId) {
return this.httpClient.get<IPerson>(this.base_url +
'api/SampleData/GetPersonsById', batchId);
}
当我看到 webApi 方法时,参数是 int 类型,在调试时我看到该值为 0。
你能帮我看看我缺少什么吗?
SampleDataController.cs
[Route("api/[controller]")]
public class SampleDataController : Controller {
[HttpGet("{id:int}")]
public Person GetPersonsById(int id)
{
return SampleDataController.personList.FirstOrDefault(x=> x.Id == id);
}
}
最佳答案
考虑到所使用的路由属性,请求需要遵循路由模板
api/SampleData/{id:int}
但是既然你使用
api/SampleData/GetPersonsById
GetPersonsById
段被视为 id
参数,并且由于它不是 int
,因此默认为 0
使用正确的格式相应地构造您的目标 URL
GetBatchDetailsById(batchId) {
var url = this.base_url + 'api/SampleData/' + batchId;
return this.httpClient.get<IPerson>(url);
}
关于c# - 当参数从 WebApi Controller 方法从 Angular 服务传递时,采用 Int 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756400/