.Net 5中的ClaimsPrincipal.HttpContext

我正在尝试在单元测试(使用.net 5预览)中模拟IPrinciple(因为我有一个使用User.Identity.Name的控制器动作,我想为其编写单元测试)。参考this question中的答案,我的单元测试中有以下内容。

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
    new Claim(ClaimTypes.Name,username),},"mock"));
userController.ControllerContext = new ControllerContext()
{
                 
    HttpContext = new DefaultHttpContext() { User = user }
};

但是,我收到以下错误消息。

Reference to type 'HttpContextBase' claims it is defined in 'system.web',but it could not be found

我看到了一个类似的问题here,但是答案指导更改目标版本。我想知道是否存在不更改目标版本的方法。

iCMS 回答:.Net 5中的ClaimsPrincipal.HttpContext

最终设法解决了这一问题,将答案留给了可能遇到类似情况的任何人。

我没有完全替换ControllerContext,而是替换了ControllerContext.HttpContext

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
    new Claim(ClaimTypes.Name,userName),},"mock"));
userController.ControllerContext.HttpContext = new DefaultHttpContext() { User = user };

这确保了控制器可以通过以下方式接收用户名

var userName = User.Identity.Name;
本文链接:https://www.f2er.com/1824625.html

大家都在问