【问题标题】:ModelState Validation Error when get value from User.Identity.GetUserId()从 User.Identity.GetUserId() 获取值时的 ModelState 验证错误
【发布时间】:2016-05-15 11:30:04
【问题描述】:

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

用户名是必填项

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

【问题讨论】:

  • 可能User 为空?
  • 没有。它不为空,因为它保存在数据库中。问题是我不能在这个属性上使用 [Required] 属性。但是删除此属性并不能确定是否传递了 userId。

标签: c# asp.net owin identity modelstate


【解决方案1】:

如果您使用的是 Web API 2,请使用 User.identity.GetUserId()

RequestContext.Principal.Identity.GetUserId()

或

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

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

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2016-05-10
    • 2010-11-24
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多