我在我的应用程序中创建更新用户,然后 我在 Postman 和 Web 应用程序中测试我的应用程序,但创建了不同的结果。 当我在 postman 中尝试此代码时,它可以工作,但网络应用程序无法工作 (ASP.NET CORE 2.0 中的代码,使用 Angular 5 的 Web 应用程序)
[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);
我检查了一下,结果是 null。
知道用户设置在哪里吗?
我的登录 Controller :
[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)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
var user = _mapper.Map<UserForDetailDto>(userFromRepo);
return Ok(new { tokenString, user });
}
最佳答案
如果 api 方法包含 [Authorize],则授权 header 将随请求一起发送。如果没有发送 header ,则您没有用户。
[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
}
关于c# - 从 ASP.NET CORE 2 获取当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49973251/