我在成功登录后尝试访问用户数据时收到NullReferenceException。此处的查询是关于在登录过程中实际可以查询用户数据的时间。以下是我在Account控制器的Login方法中放置的代码:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var sh = new SoapHelper();
var user = UserManager.FindById(User.Identity.GetUserId());
Session["UserExists"] = true;
Session["StartDate"] = DateTime.Now.ToString("yyyyMMdd");
Session["EndDate"] = DateTime.Now.ToString("yyyyMMdd");
Session["UserCompany"] = user.CompanyID;
最后一行代码是抛出错误的地方,我是否无法在登录过程中访问UserManager以从User表中获取所需的数据?
任何帮助将不胜感激!
答案 0 :(得分:0)
你的意思是说用户对象是空的吗?
angular.module('starter.services', [])
.factory('Users', function ($resource) {
return $resource('https://example.com/:id', { id: '@id' }, {
update: { method: 'PUT' }
});
})
.controller('myController', function ($scope, $ionicPopup, Users) {
// Triggered by clicking the 'add user' button in header.html
$scope.addUser = function () {
//$scope.formUser = {}; // this doesn't work
$scope.formUser = new Users(); // this works
// Show popup form
$ionicPopup.show({
templateUrl: 'templates/userform.html',
title: 'Add new user',
subTitle: 'Firstname is mandatory',
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.formUser.firstname) {
e.preventDefault(); // Prevent save if first name is empty
} else {
$scope.formUser.id = 0; // If id is left undefined, $save sends a GET method
$scope.formUser.$save()
}
}
}
]
});
};
})
请您在此处发布例外情况,以便我们提供更多详细信息。
实体框架中的users表中是否还有CompanyId列?
答案 1 :(得分:0)
经过一些研究和测试后,我发现你在SignInManager.PasswordSignInAsync的同一次调用中不能使用User.Identity.Name的原因是User.Identity填写了来自身份验证cookie的声明(其中尚未解析)。
所以我尝试了第二次调用等待UserManager
var user = await UserManager.FindAsync(model.Email, model.Password);
它就像一个魅力。