【问题标题】:Web Api User Identity returning nullWeb Api 用户身份返回 null
【发布时间】:2014-06-04 13:35:00
【问题描述】:

我以用户身份成功登录,然后该用户能够访问网站的 [已授权] 部分。用户名甚至显示在站点的右上角,因为它们已成功通过身份验证。但是,当我尝试在帖子中获取用户身份以进行新事件时,用户为空。

这是我的登录服务:

login.service('loginService', function ($http, $q) {
    var deferred = $q.defer();

    this.signin = function (user) {
        var config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }

        $http.post('Token', 'grant_type=password&username='+user.UserName+'&password='+user.Password, config)
            .success(function (data) {
                window.location = "/dashboard";
            }).error(function (error) {
                deferred.reject(error);
            });

        return deferred.promise;
    }
});

这是我发布新活动的帖子

[Route("post")]
public HttpResponseMessage PostEvent(EventEditModel ev)
{
    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "{ }");
    }
    try
    {
        Event DBEvent;
        if (ev.EventId > 0)
        {
            DBEvent = db.Events.Find(ev.EventId);
            DBEvent.ModifiedBy = Guid.Parse(User.Identity.GetUserId());
            DBEvent.ModifiedOn = DateTime.Now;
        }
        else
        {
            DBEvent = new Event();
            string id = User.Identity.GetUserId();
            DBEvent.CreatedBy = Guid.Parse(User.Identity.GetUserId());
            DBEvent.CreatedOn = DateTime.Now;
        }

        ...
}

我应该在每个帖子中传递用户信息吗?我不知道我会怎么做。还是我只是没有正确登录用户?

【问题讨论】:

  • 您好像忘记在成功回调中调用deferred.resolve(data);
  • @KhanhTO 谢谢。可能解决了未来的头痛问题,但这仍然没有解决。如果成功,我应该对那个回报做些什么吗?

标签: c# angularjs asp.net-web-api


【解决方案1】:

我偶然发现并想给出我的解决方案的老问题。离开 Dunc 的答案,然后找到 this 的帖子,我得到了答案。为了从 GetUserId() 取回一些东西,您必须使用 ClaimTypes.NameIdentifier 类型以及您想要的用户 ID 添加新声明:

ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

【讨论】:

    【解决方案2】:

    User.Identity.GetUserId() 似乎在 Web Api 中返回 null。 From what I can gather 你应该改用User.Identity.GetUserName()

    例如

    ApplicationUser user = UserManager.FindByName(User.Identity.GetUserName());
    var userId = user.Id;
    

    【讨论】:

    • User.Identity.GetUserId() 在 Microsoft.AspNet.Identity 中
    • 是的,你是对的——但它总是返回 null(至少对我来说)。答案已澄清。
    【解决方案3】:

    在创建新的 ClaimsIdentity 时,您需要使用 ClaimTypes.Name 专门为名称创建一个新的 Claim。

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 1970-01-01
      • 2021-03-18
      • 2021-08-23
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多