c# - User.Identity.GetUserId() 登录成功后返回null

标签 c# asp.net-mvc asp.net-mvc-5 identity

我定义了一个临时变量来获取当前用户 ID,它总是返回 null。

这是截图:

userId

为什么?

更新:

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return Json(new { success = false, ex = "Fail to login." });
        }

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: true, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                string userId = User.Identity.GetUserId();
                return Json(new { success = true });
            case SignInStatus.Failure:
                return Json(new { success = false, ex = "Email or password was incorrect." });
            default:
                return Json(new { success = false, ex = "Fail to login." });
        }
    }

更新 2:

在客户端,我使用ajax连接到/Account/Login:

var loginAjax = function (email, password, callback) {        
        $.ajax({
            url: '/Account/Login',
            type: 'POST',
            data: { Email: email, Password: password },
            success: function (data) {
                $('body').css('cursor', 'default');
                if (data.success) {                    
                    callback(true)
                } else {
                    $('#login-error').text(data.ex)
                }
            },
            error: function () {                
                $('#login-error').text('Không thể kết nối đến máy chủ.')
            }
        });
        callback(false)
    };


// I've got email and password in another function to check valid or not
loginAjax(email, password, function (success) {
            $('body').css('cursor', 'default');
            switch (success) {
                case true:
                    signin(function () {
                        $('.login').html('');
                        window.location.href = '/?type=Promotion';
                    });
                    break
                case false:                    
                    $('#Email-active').hide();
                    $('#Password-active').hide();
                    $('#Password').val('');
                    $('#login-btn').removeClass('disabled').attr('onclick', '$(this).addClass("disabled").removeAttr("onclick"); running()');
                    break
            }
        });

客户端的 SignalR:

var signalR = $.connection.chat;
var signin = function (callback) {
            $.connection.hub.start().done(function () {
                signalR.server.signinToSignalR();
                callback()
            })
        };

服务器端的 SignalR:

public void SigninToSignalR()
    {
        // this's always null
        string userId = HttpContext.Current.User.Identity.GetUserId();
    }

最佳答案

简单地试试这个:

string userId = SignInManager
.AuthenticationManager
.AuthenticationResponseGrant.Identity.GetUserId();

关于c# - User.Identity.GetUserId() 登录成功后返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951881/

相关文章:

asp.net-mvc-5 - 如何配置用户上下文/表?

c# - 具有一对多关系的 Entity Framework 对象的序列化

c# - 根据当前文化将字符串转换为带点或逗号的十进制

jquery - ASP.NET MVC5 Bootstrap 3 Modal Form 不验证客户端并回发到页面

Asp.net MVC VirtualPathProvider View 解析错误

c# - 如何在 ASP.NET MVC 中的应用程序生命周期中仅初始化和取消初始化一次

c# - 有什么方法可以用 ClrMD 获取局部变量的值(比如 sosex !mdv)?

c# - 定位windows系统日期时间时钟窗口

asp.net-mvc - 如何自动设置输入字段的 MAXLENGTH?

C# 互操作字、剪切和粘贴适用于 Office 2016,但不适用于 Office 2019