我有一个使用Identity的.NET Core 3.1项目。对于Login
页面处理程序,我已经添加了一行代码,在用户登录后,它会根据他们的IP地址更新用户位置:
_locationRepository.UpdateUserLocationAsync(HttpContext.Connection.RemoteIpAddress);
完整代码
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_locationRepo.UpdateUserLocation(HttpContext.Connection.RemoteIpAddress);
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
我的问题是在编写单元测试时,我不知道如何正确地模拟
HttpContext
。无论我尝试了什么,都会一直收到空引用异常的错误提示。var httpContext = new Mock<HttpContext>();
httpContext.Setup(x => x.Connection.RemoteIpAddress).Returns(new IPAddress(16885952));
我该如何模拟远程IP地址
?