首页 > 解决方案 > Angular 到 ASP.NET Core API - JSON 值无法转换为 System.String

问题描述

使用 ASP.NET Core 5 我有以下控制器和模型:

[HttpPost("users/{userId:int:min(1)}/confirm-email")]
public async Task<IActionResult> ConfirmEmail(Request request) {
  Response response = await _service.Send(request);
  return Ok(response);
}

public class Request { 
  [FromRoute] public Int32 UserId { get; set; }
  [FromBody] public String Token { get; set; }
}

public class Response { } 

在 Angular 上,我使用以下方法调用 API:

const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

var userId = 1;

httpClient.post<Response>(`${this.url}/users/${userId}/email/confirm-email`, { token: "test" } , { headers: headers });

在控制器上,我得到了UserId值,但随后我得到了令牌错误:

The JSON value could not be converted to System.String. Path: $

ModelState 上的 Key 不是 Token 而是$. 因为UserId关键是UserId

我不知道为什么会这样……知道吗?

标签: angularasp.net-coreasp.net-core-5.0angular12

解决方案


除非我读错了,否则路线是不同的。

users/{userId:int:min(1)}/confirm-email

与您发布的内容不同

`${this.url}/users/${userId}/email/confirm-email`

该路线没有/email/confirm-email。它只是确认电子邮件。


推荐阅读