I would like to test web service call with user identity set ( pretending the user is logged in)
I have checked numerous posts and stackoverflow answers but I didn't quite get the answer I want.
The closest I got is this.
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");
And at this point, I presume I have to set the controllercontext and that context variable needs to be fed somehow.
I have seen a lot of examples regarding MVCcontrollers but I couldn't find the one that works for an ApiController. Can someone please shed some light on this?
Thanks!
This is what I did for my project: For 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", "[email protected]"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "live.com#[email protected]")
})
);
And this is for .net core 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 }
};
Let me know if it helps or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With