从 User.Identity.GetUserId() 获取值时出现 ModelState 验证错误

ModelState Validation Error when get value from User.Identity.GetUserId()

在我的 WebApi 控制器 post 函数中,我通过 User.identity.GetUserId() 将用户 ID 分配给了我的 posted 对象,但是 ModelState.isValid 总是 return 验证错误

user id is required

同时将值分配给所需的属性。所以我从 userId 属性 中删除了必需的属性。它正在工作,但我需要知道为什么 ModelState 不知道 User.Identity.GetUserId() 已经提供了用户 ID。

如果您使用的是 Web API 2,请使用

而不是 User.identity.GetUserId()
RequestContext.Principal.Identity.GetUserId()

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

Request.GetOwinContext().GetUserManager<ApplicationUserManager>()