C# 在使用moq和nunit测试web api控制器时,如何模拟用户身份?

C# 在使用moq和nunit测试web api控制器时,如何模拟用户身份?,c#,asp.net-web-api2,moq,C#,Asp.net Web Api2,Moq,我想使用用户标识集测试web服务调用(假装用户已登录) 我检查了很多帖子和答案,但我没有得到我想要的答案 我得到的最接近的是这个 var context = new Mock<HttpContextBase>(); var mockIdentity = new Mock<IIdentity>(); context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object); mockIdentity.Set

我想使用用户标识集测试web服务调用(假装用户已登录)

我检查了很多帖子和答案,但我没有得到我想要的答案

我得到的最接近的是这个

var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x => x.Name).Returns("abc");
var context=newmock();
var mockIdentity=new Mock();
SetupGet(x=>x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x=>x.Name).Returns(“abc”);
在这一点上,我假设我必须设置controllercontext,并且需要以某种方式输入上下文变量

我看过很多关于MVC控制器的例子,但是我找不到一个适用于ApicController的。有人能解释一下吗


谢谢

这就是我为我的项目所做的: 对于ASP.NET Web Api

this._userController.User = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new List<Claim>
                    {
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1234"),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "Test@test.com"),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "live.com#Test@test.com")
                    })
                );

让我知道它是否有用。

Awww,它太简单了

var identity = new GenericIdentity("bcd");

Controller.User = new GenericPrincipal(identity, null);

原来这部分不需要模仿用户,你只需要设置你正在调用的控制器的用户ID。

谢谢你的帖子,我会测试并给你更新!我已尝试了您的建议,并且添加到索赔标识的索赔项目未经RequestContext.Principal.identity.Name或User.identity.Name检查(即未设置名称值)。检查身份下的声明是否是一种标准做法?谢谢Hung,您的.net核心web api帮助我解决了问题。
var identity = new GenericIdentity("bcd");

Controller.User = new GenericPrincipal(identity, null);