为了账号安全,请及时绑定邮箱和手机立即绑定

从ASP.NET CORE 2获取当前用户

从ASP.NET CORE 2获取当前用户

C#
慕沐林林 2021-05-05 13:08:51
我在App中创建了更新用户,然后在Postman和Web App中测试了我的应用,但创建了不同的结果。当我在邮递员中尝试此代码时,它可以工作,但Web应用程序不起作用(ASP.NET CORE 2.0中的代码,使用Angular 5的Web App)[HttpPut("{id}")]    public async Task<IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userDto) {        if(!ModelState.IsValid)            return BadRequest(ModelState);        var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);        var userFromRepo = await _orgRepo.GetUser(id);        if(userFromRepo == null)             return NotFound($"User not found with id: {id}");        if (currentUserId != userFromRepo.Id)            return Unauthorized();        _mapper.Map<UserForUpdateDto, User>(userDto, userFromRepo);        if (await _orgRepo.SaveAll())            return NoContent();        throw new Exception($"Updating user {id} failed on save");    }从WebApp产生错误:“对象引用未设置为对象的实例。”当我调试应用程序时,似乎是由线引起的var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);我检查,它产生空值。知道在哪里设置用户吗?我的登录控制器:[HttpPost("login")]    public async Task<IActionResult> Login([FromBody]UserForLoginDto userForLoginDto)    {        var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);        if (userFromRepo == null)            return Unauthorized();        // generate token        var tokenHandler = new JwtSecurityTokenHandler();        var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);        var tokenDescriptor = new SecurityTokenDescriptor        {            Subject = new ClaimsIdentity(new Claim[]            {                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),                new Claim(ClaimTypes.Name, userFromRepo.Username),                new Claim(ClaimTypes.Role, "RegisteredUsers")            }),            Expires = DateTime.Now.AddDays(3),            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),                SecurityAlgorithms.HmacSha512Signature)        };
查看完整描述

1 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

如果api方法包含[Authorize],则将与请求一起发送授权标头。如果未发送头,则您没有用户。


[HttpPut("{id}")]

[Authorize(AuthenticationSchemes = "Bearer")]

public async Task<IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userDto) 

   {    

       var sub = User.GetSubjectId();   // Subject Id is the user id

    }


查看完整回答
反对 回复 2021-05-08
  • 1 回答
  • 0 关注
  • 178 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信