Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prywatna klasa?
public static class ControllerExtensions
{
public static string GetUserClaim(this ApiController controller, string claimName)
{
var principal = controller.User as ClaimsPrincipal;
if (principal == null)
{
return null;
}
var claim = principal.Claims.FirstOrDefault(c => c.Type == claimName);
if (claim == null)
{
return null;
}
return claim.Value;
}
public static T GetUserClaim<T>(this ApiController controller, string claimName)
{
var val = controller.GetUserClaim(claimName);
return (T)Convert.ChangeType(
val,
typeof(T)
);
}
}
public class ControllerExtensionsTest
{
private string _claimName = "userId";
private int _claimValue = 123;
private TestController Create()
{
var controller = new TestController();
controller.User = new ClaimsPrincipal(new ClaimsIdentity(new [] {new Claim(_claimName, _claimValue.ToString())}));
return controller;
}
[Fact]
public void GetUserClaim_Return_Null_When_User_Is_Null()
{
var controller = Create();
controller.User = null;
var claim = controller.GetUserClaim("claimName");
claim.Should().BeNull();
}
[Fact]
public void GetUserClaim_Return_Null_When_Claim_Does_Not_Exist()
{
var controller = Create();
var claim = controller.GetUserClaim("claimName");
claim.Should().BeNull();
}
[Fact]
public void GetUserClaim_Return_Claim()
{
var controller = Create();
var claim = controller.GetUserClaim(_claimName);
claim.Should().NotBeNull();
claim.Should().Be(_claimValue.ToString());
}
[Fact]
public void Generic_GetUserClaim_Return_Claim()
{
var controller = Create();
var claim = controller.GetUserClaim<int>(_claimName);
claim.Should().Be(_claimValue);
}
private class TestController : ApiController
{
}
}
public class OuterClass
{
private class InnerClass
{
}
}
private class PrivateClass
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.