TypeScript 将方法名称而不是参数值传递给 .Net Core



为什么下面的代码在登陆.Net Core 3.1端时最终将"getFullReport"作为eventId传递,而不是实际的eventId值?

在调用之前,我已经在这里用一个console.log语句验证eventId是我希望在 .Net Core 端看到的正确 ID,但是当我在那里设置断点时,eventId显示为 TypeScript 方法的名称 (getFullReport(,而不是在客户端调用之前显示的 ID。

getFullReport(eventId: string) {
var params = new HttpParams();
params.append('eventId', eventId);
this.http.get<AccidentDetails>('api/accidents/getfullreport', { params: params }).subscribe(
result => {
this.accidentDetails = result;
},
error => console.error(error)
);
}

.Net Core 代码是:

[HttpGet("{eventId}")]
public FullReport GetFullReport(string eventId)

此事件 ID 不是我尝试从客户端发送的事件 ID。

HttpGet属性内的参数是终结点的路由。当您将变量的名称(如:{variable_name}(放入路由中时,这意味着您应该将该路径的标记映射到具有相应名称的变量。因此,您看到eventId等于getFullReport,因为您已按如下方式设置路径:api/accidents/getFullReport这意味着您正在api/accidents/{eventId}eventId=getFullReport的路径上。这有意义吗?

要解决此问题,请执行以下操作:

[HttpGet("getFullReport/{eventId}")]
public FullReport GetFullReport(string eventId)

我根据Matt Kae的建议答案更改了.Net Core端的属性:

[HttpGet("GetFullReport/{eventId}")]

然后我删除了 TypeScript 中的params代码,并通过将eventId直接附加到 URL 调用中来调用它:

this.http.get<AccidentDetails>('api/Accidents/GetFullReport/' + eventId).subscribe()

这解决了问题。

最新更新