这是我的做法,但我没有使用 WCF 执行此操作的经验。请注意,这需要引用 System.Web。
/// <summary>
/// Returns the user name of the current user. Gets user name from HttpContext if running as a web app, else WindowsIdentity.
/// </summary>
private static string GetUserName()
{
var identity = HttpContext.Current == null ? WindowsIdentity.GetCurrent() : HttpContext.Current.User.Identity;
if (identity == null)
{
throw new Exception("Identity could not be determined.");
}
// Remove domain name if present
var s = identity.Name;
var stop = s.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase);
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1).ToUpper() : s;
}