我想测试带有用户身份集的 web 服务调用(假装用户已登录)
我检查了很多帖子和 stackoverflow 的答案,但我没有完全得到我想要的答案。
我得到的最接近的是这个。
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");
此时,我假设我必须设置 controllercontext 并且需要以某种方式提供该上下文变量。
我看过很多关于 MVC Controller 的示例,但我找不到适用于 ApiController 的示例。有人可以解释一下吗?
谢谢!
最佳答案
这是我为我的项目所做的: 对于 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")
})
);
这是 .net 核心 web api:
var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, "testId"),
new Claim(ClaimTypes.Name, "testName")
}));
this.controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()
{
HttpContext = new DefaultHttpContext() { User = user }
};
如果有帮助,请告诉我。
关于c# - 使用最小起订量和 nunit 测试 web api Controller 时如何模拟用户身份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547144/