What’s My Name?

Use the Win32 GetUserName function to get a request’s Windows identity.





What's My Name?

Use the Win32 GetUserName function to get a request's Windows identity.


By Jeff Prosise


Q: How can I get the name of the Windows security principal that a request is executing as? Page.User.Identity.Name is no help at all when forms authentication is being used.


A: The easiest way is to use the .NET Framework's interop support to call the Win32 GetUserName function; the ASPX file in Figure 1 demonstrates the process. I've used code successfully like this before to debug security problems.


<%@ Import Namespace="System.Runtime.InteropServices" %>




    <asp:Label ID="Output" RunAt="server" />




<script language="C#" runat="server">

[DllImport ("Advapi32.dll")]

static extern bool GetUserName (StringBuilder name,

    ref int size);


void Page_Load (Object sender, EventArgs e)


    StringBuilder name = new StringBuilder (1024);

    int size = name.Capacity;

    if (GetUserName (name, ref size))

        Output.Text = name.ToString ();



Figure 1. The Win32 GetUserName function displays the Windows identity of the current thread.


For this sample to work, it must run with a high enough trust level to permit callouts to unmanaged code. ASP.NET defaults to running with full trust, which is more than sufficient to call Win32 API functions.


Jeff Prosise is the author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET. Contact Jeff at [email protected].





Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.