gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:09:06 28 4
gpt4 key购买 nike

我定义了一个临时变量来获取当前用户 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com