Archiv der Kategorie: MVC

MVC – Show User’s Fullname

  1. Add Reference to „System.Directory.AccountManagement“
  2. Set „Copy Local“ to True
  3. Add following XML Snippet to „Web.Config“
    <compilation debug=“true“ targetFramework=“4.5.2″ >
    <add assembly=“System.DirectoryServices, Version=,Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A“ />
  4. Add Folder „App_Code“ to your Project
  5. Add a new Item „Helper – cshtml“ inside this Folder
  6. Change „Views/Shared/_Layout.cshtml“
    Hello, @User.Identity.Name!
    Hello, @UserNameHelper.UserFullName()!

UnitTest – How to Mock „User.Identity.GetUserId()“

ILSpy shows for GetUserId():

Public static string GetUserId(this IIdentity identity)
if (identity == null)
throw new ArgumentNullException(„identity“);
ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
if (claimsIdentity != null)
return claimsIdentity.FindFirstValue(;
return null;

So you need to mock the Extension Method „GetUserId()“ a claim based User-Moq-Object:

var identity = new GenericIdentity(„“);
identity.AddClaim(new Claim(„“, „1“));
var principal = new GenericPrincipal(identity, new[] { „user“ });
context.Setup(s => s.User).Returns(principal);

var controller = new YOURController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);